Dijkstra Algorithm Visualizer
Watch the Shortest Path Get Built, One Step at a Time
A free tool for CS students: draw a weighted graph, press Step, and see how every distance is checked, updated and finalised.
Dijkstra’s algorithm on a six-node graph: the shortest path from A to F is highlighted.
Home → CS Student Hub → Dijkstra Algorithm Visualizer
This Dijkstra algorithm visualizer lets you draw your own weighted graph, pick a start node and watch every step of the shortest path search: which node is chosen, which distances are updated and why. Switch on a negative edge to see exactly where Dijkstra’s algorithm goes wrong, and when to use Bellman-Ford instead.
Dijkstra Algorithm Visualizer: Build and Run Your Own Graph
Unlock Your Potential
Turn your highest ambitions into everyday reality. You set the standard and aim for the goal; when you’re ready for what comes next, we help you cross the finish line.
Own Your Future →Dijkstra’s Algorithm Step by Step
Dijkstra’s algorithm finds the shortest path from one start node to every other node in a weighted graph, as long as no edge weight is negative. Edsger W. Dijkstra designed it in 1956 and published it in 1959; the Wikipedia article on Dijkstra’s algorithm covers the history in more detail. It is a greedy algorithm: at every step it picks the closest node it has not finished yet and treats that distance as final.
Here is Dijkstra’s algorithm step by step, in five moves:
- Set the start node’s distance to 0 and every other node’s distance to infinity (∞).
- Put the start node in a priority queue, which always hands back the node with the smallest distance.
- Remove the node with the smallest distance from the queue. Its distance is now final.
- For each neighbour that is not final yet, add the edge weight to the current node’s distance. If the total is smaller than the neighbour’s recorded distance, update it and remember the current node as its previous node.
- Repeat steps 3 and 4 until the queue is empty.
Press Step in the Dijkstra algorithm visualizer above and you will see each of these moves: the gold node is the one just picked, green nodes are final, and the “What is happening” panel explains the arithmetic in plain words.
To read the answer, follow the Previous column backwards from the end node to the start node. That chain of previous nodes is the shortest path, and it is how the tool draws the highlighted route.
Dijkstra Algorithm Example with a Distance Table
This Dijkstra algorithm example uses the Classroom graph from the Dijkstra algorithm visualizer, starting at A. Each row of the table shows every node’s distance after one more node has been finalised. Load the Classroom graph above and step through it to watch the same numbers appear.
| After finalising | A | B | C | D | E | F |
|---|---|---|---|---|---|---|
| Start | 0 | ∞ | ∞ | ∞ | ∞ | ∞ |
| A | 0 | 4 | 2 | ∞ | ∞ | ∞ |
| C | 0 | 3 | 2 | 10 | 12 | ∞ |
| B | 0 | 3 | 2 | 8 | 12 | ∞ |
| D | 0 | 3 | 2 | 8 | 10 | 14 |
| E | 0 | 3 | 2 | 8 | 10 | 13 |
| F | 0 | 3 | 2 | 8 | 10 | 13 |
The bold numbers are the interesting moments, where a shorter route replaces an earlier guess:
- B drops from 4 to 3. The direct edge A–B costs 4, but going A → C → B costs 2 + 1 = 3.
- D drops from 10 to 8. The first guess went through C (2 + 8); the route through B (3 + 5) is shorter.
- E drops from 12 to 10 and F from 14 to 13. Each improvement comes from the node finalised just before it.
The shortest path from A to F is therefore A → C → B → D → E → F with a total cost of 13.
Why Dijkstra’s Algorithm Fails with Negative Weights
The greedy step assumes that once a node is the closest unfinished node, nothing can make it closer later. That is true only when every edge weight is zero or more: any other route to the node has to pass through nodes that are at least as far away, and extra edges can only add distance. A negative edge breaks that assumption, and this is the heart of the Dijkstra negative weights problem.
Load the Negative edge demo in the Dijkstra algorithm visualizer (it is a directed graph). From A the edges are A → B = 1, A → C = 4, C → B = −5, B → D = 2 and D → E = 3. Dijkstra finishes B with distance 1, because B is the closest node at that moment. Later it reaches C and sees that C → B would give 4 + (−5) = −1, but B is already final, so the edge is ignored.
| B | D | E | |
|---|---|---|---|
| Dijkstra’s answer | 1 | 3 | 6 |
| True shortest distance | −1 | 1 | 4 |
The tool shows this in the “True (Bellman-Ford)” column and warns you when Dijkstra’s answer is wrong.
What to use instead. The Bellman-Ford algorithm handles negative edges and also detects negative cycles, loops whose total weight is below zero, where the “shortest” path would keep shrinking forever. In an undirected graph even a single negative edge forms such a cycle, because you can walk back and forth along it. Zero-weight edges are fine for Dijkstra; only negative ones cause trouble.
Dijkstra vs Bellman-Ford vs BFS: Which to Use
All three find shortest paths, but each fits a different kind of graph. V is the number of nodes and E the number of edges.
| BFS | Dijkstra | Bellman-Ford | |
|---|---|---|---|
| Edge weights | All equal (unweighted) | Zero or positive | Any, including negative |
| Negative cycles | Not applicable | Not detected; wrong results | Detected |
| Time | O(V + E) | O((V + E) log V) with a binary heap | O(V × E) |
| Typical use | Fewest steps, mazes | Maps, network routing | Graphs with negative costs |
Rule of thumb: if every edge counts the same, use BFS. If edges have different non-negative costs, use Dijkstra. If any edge can be negative, use Bellman-Ford.
Dijkstra Algorithm Code: Python and C++
Both programs below build the Classroom graph from the worked example and print the same distances the Dijkstra algorithm visualizer shows (A: 0, B: 3, C: 2, D: 8, E: 10, F: 13). They use a priority queue and skip outdated queue entries instead of changing a value inside the queue, which is the usual way to write it.
Python
import heapq
def dijkstra(graph, start):
dist = {node: float("inf") for node in graph}
prev = {node: None for node in graph}
dist[start] = 0
heap = [(0, start)]
while heap:
d, u = heapq.heappop(heap)
if d > dist[u]:
continue # outdated queue entry, skip it
for v, w in graph[u]:
nd = d + w
if nd < dist[v]:
dist[v] = nd
prev[v] = u
heapq.heappush(heap, (nd, v))
return dist, prev
def path_to(prev, target):
path = []
while target is not None:
path.append(target)
target = prev[target]
return path[::-1]
graph = {
"A": [("B", 4), ("C", 2)],
"B": [("A", 4), ("C", 1), ("D", 5)],
"C": [("A", 2), ("B", 1), ("D", 8), ("E", 10)],
"D": [("B", 5), ("C", 8), ("E", 2), ("F", 6)],
"E": [("C", 10), ("D", 2), ("F", 3)],
"F": [("D", 6), ("E", 3)],
}
dist, prev = dijkstra(graph, "A")
print(dist)
print(" -> ".join(path_to(prev, "F")), "cost", dist["F"])
C++
#include <bits/stdc++.h>
using namespace std;
int main() {
const int INF = INT_MAX;
int n = 6; // nodes 0..5 = A..F
vector<vector<pair<int, int>>> g(n); // (neighbour, weight)
auto addEdge = [&](int u, int v, int w) {
g[u].push_back({v, w});
g[v].push_back({u, w});
};
addEdge(0, 1, 4); addEdge(0, 2, 2); addEdge(1, 2, 1);
addEdge(1, 3, 5); addEdge(2, 3, 8); addEdge(2, 4, 10);
addEdge(3, 4, 2); addEdge(3, 5, 6); addEdge(4, 5, 3);
vector<int> dist(n, INF), prev(n, -1);
priority_queue<pair<int, int>, vector<pair<int, int>>, greater<>> pq;
dist[0] = 0;
pq.push({0, 0});
while (!pq.empty()) {
auto [d, u] = pq.top();
pq.pop();
if (d > dist[u]) continue; // outdated queue entry
for (auto [v, w] : g[u]) {
if (d + w < dist[v]) {
dist[v] = d + w;
prev[v] = u;
pq.push({dist[v], v});
}
}
}
for (int i = 0; i < n; i++)
cout << char('A' + i) << ": " << dist[i] << "\n";
return 0;
}
Time and space complexity
With a binary heap, Dijkstra’s algorithm runs in O((V + E) log V) time and uses O(V + E) space for the graph plus O(V) for the distances. A plain array in place of the heap gives O(V²), which is actually faster on very dense graphs where E is close to V². A Fibonacci heap improves the bound to O(E + V log V) in theory, but binary heaps are simpler and usually faster in practice.
Where Dijkstra’s algorithm is used
Map and navigation apps use it, or close relatives of it, to find the quickest road route. Internet routing protocols such as OSPF run it to choose paths between routers. Games and robots use A*, which is Dijkstra’s algorithm with an extra estimate of the distance still to go, to steer characters around obstacles.
Dijkstra’s Algorithm Practice Problems
Try each problem on paper first, then build the graph in the Dijkstra algorithm visualizer (choose Blank canvas, Add node and Add edge) to check your answer. Click a question to reveal the answer.
Problem 1: Undirected graph with edges S–A = 2, S–B = 5, A–B = 1, A–C = 4, B–C = 1, B–D = 7, C–D = 3. Start at S. In what order are the nodes finalised, and what is the shortest path from S to D?
Order and distances: S (0), A (2), B (3), C (4), D (7). B improves from 5 to 3 through A (2 + 1), and C settles at 4 through B (3 + 1). The shortest path from S to D is S → A → B → C → D with cost 7.
Problem 2: Directed graph with edges A → B = 2, A → C = 3, C → B = −2. Start at A. What distance for B does Dijkstra’s algorithm report, and is it correct?
Dijkstra picks B first (distance 2) and makes it final. When it later reaches C, the edge C → B would give 3 + (−2) = 1, but B is already final, so the edge is ignored. It reports 2, but the true shortest distance is 1 (A → C → B). Bellman-Ford finds the correct value.
Problem 3: Directed graph with edges P → Q = 3, P → R = 2, R → Q = −2. Start at P. There is a negative edge, so is Dijkstra’s answer wrong here?
No, it happens to be correct. Dijkstra picks R (2) before Q (3), and when it checks R → Q, Q is not final yet, so it updates Q to 2 + (−2) = 0, which is the true shortest distance. A negative edge only causes a wrong answer when it points to a node that has already been finalised. Dijkstra gets lucky here, which is why you should not rely on it when negative edges exist.
Problem 4: A graph has 1,000 nodes and 5,000 edges. Which is faster, the array version at O(V²) or the binary-heap version at O((V + E) log V)?
The array version needs about 1,000² = 1,000,000 steps. The heap version needs about (1,000 + 5,000) × log₂(1,000), roughly 6,000 × 10 = 60,000 steps. The binary heap is far faster here because the graph is sparse. The array version only wins when E is close to V².
Dijkstra Algorithm Visualizer FAQ
What does a Dijkstra algorithm visualizer show?
Like any good shortest path visualizer, it shows the search one step at a time: which node is picked, which edge is checked, how each distance changes and which node becomes final. Seeing the distance table and priority queue update together makes the algorithm much easier to understand than reading code alone.
Can Dijkstra’s algorithm handle negative edge weights?
No. It can return wrong distances, because it finalises a node as soon as it is the closest one and never revisits it. Use the Bellman-Ford algorithm for graphs with negative edges. The Negative edge demo in the Dijkstra algorithm visualizer shows the failure and compares it with the correct answer.
Does it work on both directed and undirected graphs?
Yes. Dijkstra’s algorithm works on both. In the tool, use the Graph type menu to switch between undirected (two-way edges) and directed (one-way edges).
What is the time complexity of Dijkstra’s algorithm?
O((V + E) log V) with a binary heap, where V is the number of nodes and E the number of edges. With a simple array instead of a heap it is O(V²).
How do you get the actual path, not just the distance?
Store a previous node for every node whenever its distance is updated. When the algorithm ends, start at the end node and follow the previous nodes back to the start, then reverse the list. The Previous column in the distance table shows exactly this.
What is the difference between Dijkstra’s algorithm and A*?
A* adds a heuristic, an estimate of the remaining distance to the goal, so it explores fewer nodes when you only need the path to one target. With a heuristic of zero, A* behaves exactly like Dijkstra’s algorithm.
More Free Tools for CS Students
After the Dijkstra algorithm visualizer, keep practising with the other interactive tools on CS Student Hub:
Stuck on a Graph Problem? Ask Us
Not sure why your distances do not match the Dijkstra algorithm visualizer, or want help tracing your own graph? Send us your question and we will reply by email.
Submit Your Question — Get a Step-by-Step Explanation
We will review your graph and your question and email you a clear walk-through, usually within 24-48 hours. Free. No strings attached.
📋 Before you submit:
- List your nodes and edges with their weights
- Tell us which node you start from
- Tell us where you are getting confused
Fill out the form below
🔒 Your email is safe with us. We will never share your information.
⚠️ Important Disclaimer
We aim to respond within 24-48 hours, but response times may vary. Our guidance is meant to help you learn, not to replace your own work or your professor’s instruction.
Get More CS Resources
Subscribe to get new visualizers, practice problems and CS study guides delivered to your inbox.
No spam. Unsubscribe anytime.
