Dijkstra's algorithm finds the shortest paths from one source vertex to every other vertex of a weighted graph with non-negative weights, always taking the closest unsettled vertex next. With a binary heap as its priority queue it runs in O((V + E) log V) time. This page explains how it works, with a step-by-step animation of Dijkstra's algorithm and its distance table on a directed graph from the VisiGrab app.
// how dijkstra's algorithm works
Dijkstra's algorithm finds the shortest paths, those of least total weight, from one source vertex to every other vertex of a weighted graph whose weights are 0 or more. One run fills a table with each vertex's distance from the source and its predecessor, the vertex just before it on a shortest path. Together the predecessors form a shortest-path tree.
Edsger W. Dijkstra (pronounced DYKE-struh) designed it in 1956 and published it in 1959. It works the same on directed and undirected graphs: an undirected edge counts as two directed edges of equal weight.
A vertex is settled once its distance is final. Until then its distance is tentative: the best found so far, which a shorter route may still replace. The app says inspected for settled, and puts a check icon on a vertex once its edges are relaxed in step 3.
1. Initialize: give the source distance 0 and every other vertex ∞, with no predecessors. Put all the vertices in a priority queue, which always hands out the one with the smallest distance; a min-heap is the usual choice.
2. Take the closest vertex: remove the unsettled vertex with the smallest distance and settle it. This step is greedy: it compares totals from the source, not single edges. It can also be read as dynamic programming, since each shortest path is a shortest path to the vertex before it, plus one edge.
3. Relax its edges: for each edge leaving it, add the edge's weight to its distance. If the sum is smaller than the distance recorded at the edge's end, write the sum there and make the settled vertex that end's predecessor. This test is called relaxing the edge.
4. Repeat steps 2 and 3 until the queue is empty. A vertex still at ∞ cannot be reached. For one target, the loop can stop once the target is settled; the other distances may then still be tentative.
5. Read the path back: follow the predecessors from the target to the source, then reverse the list.
The closest vertex is final: any other route to it must first pass another unsettled vertex, which already costs at least as much, and edges of weight 0 or more cannot bring the total back down.
The app's code fills the table in computePaths and rebuilds a path in getShortestPathTo. In pseudocode, with those names and shorter variable names (distance for distanceFromSourceMap, u for closestToSource, alt for alternativeDistance):
pQ = empty priority queue
for each vertex v
if v == source
distance[v] = 0
else
distance[v] = infinity
predecessor[v] = none
pQ.add(v, distance[v])
while pQ is not empty
u = pQ.pollSmallest()
for each neighbor n of u
alt = distance[u] + w(u, n)
if alt < distance[n]
pQ.update(n, alt)
distance[n] = alt
predecessor[n] = u
getShortestPathTo(target)
path = empty list
v = target
while v is not none
path.add(v)
v = predecessor[v]
reverse(path)
return path
pollSmallest removes the closest vertex, and update is what heaps call decrease-key. w(u, n) is the weight of the edge u → n. The test alt < distance[n] is the relaxation, so an equally short route keeps the old predecessor. Edges to settled vertices are tried too, but without negative weights they never pass; the player leaves them out. For a target never reached, getShortestPathTo returns the target alone, as the app's code does, so first check that distance[target] is not infinity.
The player below runs Dijkstra's algorithm from A on the app's default graph with its distance table, then reads the path to F back through the predecessors. The shortest path to F, A → B → C → E → F, weighs 18. A written distance can still drop: E gets 17 by the edge B → E, then 11 by way of C.
When some edge weights are negative: a settled distance is then not always final, and the table can end with distances that are too large, as the example below shows. Use Bellman-Ford instead.
With A → B 2, A → C 4, C → B −3 and B → D 1, Dijkstra takes B at 2 and gives D 3, then takes D, and only then C, at 4. The edge C → B now offers B a route of weight 1, and D one of weight 2. But B has left the queue for good, so the pseudocode above never tries B → D again: D keeps 3. Heap code that only skips stale entries takes B again and repairs D, but such repeats can take exponential time.
A negative cycle, whose weights add up to less than 0, leaves no shortest path at all, since each lap lowers the total. In an undirected graph one negative edge is such a cycle, crossed there and back. Adding a constant to every weight does not help, since routes with more edges gain more: with A → B −2, B → C −2 and A → C −3, the shortest route to C is A → B → C, at −4, but after adding 3 the direct edge, at 0, wins. Bellman-Ford handles negative weights, as does relaxing the edges in topological order when the graph has no cycle.
The cost depends on the priority queue. A plain array is scanned for the smallest distance, O(V) per vertex: O(V2) in all, as fast as any heap on a dense graph, where E is close to V2. Fibonacci heaps are rarely used: their constants are large. Extra space is O(V).
| Priority queue | Take smallest | Update | Total time |
|---|---|---|---|
| Plain array | O(V) | O(1) | O(V2) |
| Binary heap | O(log V) | O(log V) | O((V + E) log V) |
| Fibonacci heap | O(log V) amortized | O(1) amortized | O(E + V log V) |
Standard library heaps have no update, so the vertex is pushed again with its new distance, and a popped entry whose distance is larger than the table's is skipped. This lazy deletion pushes one entry per successful relaxation, at most E + 1, and log E is at most 2 log V: the time stays O((V + E) log V), and the space becomes O(E).
When every edge weighs the same, Dijkstra settles the vertices level by level, as breadth-first search does with a plain queue in O(V + E). Fewest edges is not least weight, though: on the player's graph BFS reaches F by A → B → C → F, three edges weighing 24, while the shortest path has four edges and weighs 18.
Bellman-Ford relaxes every edge V − 1 times, in O(V·E): slower, but it accepts negative weights and detects a negative cycle. A* adds an estimate of the distance left to one target, so it usually settles fewer vertices; Dijkstra is A* with an estimate of 0. Prim's minimum spanning tree algorithm runs the same loop, keyed by single edge weights instead of totals.
| Dijkstra | BFS | Bellman-Ford | |
|---|---|---|---|
| Time | O((V + E) log V) | O(V + E) | O(V·E) |
The app's code gives the same table and paths in all three languages. Its priority queue is a sorted array, kept simple for clarity, so each update costs O(V). Code built on a standard library heap uses lazy deletion, and the heap must hand out the smallest distance first.
Note
C++'s std::priority_queue keeps the largest element on top. Give it std::greater so that the smallest distance comes out first.
The full source code is on GitHub, in Python, Java and C++.
// in the app
In VisiGrab, Dijkstra's algorithm runs on four example graphs with its distance table, a check mark on each inspected vertex and a message for every step.
The Examples dialog remembers your pick. Besides this graph, one finds a second route to F of the same weight and keeps the first, one lowers F's distance twice, and in one F is settled before C, whose edges all lead to inspected vertices.
In the Graph Constructor, choose Dijkstra, draw a directed graph of up to 12 vertices with weights from 1 to 99, tap Apply, then tap a start and an end vertex. Each Next draws the shortest path one vertex further, and if no route exists, the app says so.
The info dialog explains the idea on a small graph of its own, compares O(V²), O((V + E) log V) and O(E + V log V) by the queue used, says why negative weights call for Bellman-Ford, and names GPS navigation.
The listing fills the distances and a predecessor map, and a second method walks back from a vertex and reverses the list. Three key points explain predecessors, the priority queue and relaxation, with a link to the full source on GitHub.
Eight questions with an explanation for every option: what one run finds, the starting distances, the next vertex, a leftover ∞, predecessors, negative weights, directed or undirected, and what sets the running time.
Bellman-Ford finds shortest paths when some weights are negative, and in the Graph Constructor it reports a negative cycle. Prim and Kruskal build minimum spanning trees, and Breadth-First Search counts edges instead of weights.
// build your own
Download VisiGrab to watch the distance table fill in on four example graphs, then draw a weighted graph of your own and find a shortest path in it.
Dijkstra's algorithm is one of 30+ topics. See them all