Dijkstra's Algorithm, step by step.

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

What is Dijkstra's algorithm?

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.

How does Dijkstra's algorithm work? Relaxation and the closest vertex

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.

Dijkstra's algorithm pseudocode, with the path read back

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.

Dijkstra's algorithm example: a distance table step by step

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.

Dijkstra's algorithm on a directed graph

All steps as text
  1. Find the shortest paths from A to all vertices in the directed graph using Dijkstra's algorithm.
  2. Use the table to track distances from A to every vertex. Unknown distances are marked as ∞.
  3. Start from vertex A.
  4. Check distances to A's neighbors.
  5. Compute the distance from A to B: 5.
  6. Record 5 as AB's distance and set A as B's predecessor. Update the distance and predecessor if a shorter route to B is found later.
  7. Compute the distance from A to D: 8.
  8. Record 8 as AD's distance and set A as D's predecessor. Update the distance and predecessor if a shorter route to D is found later.
  9. Mark vertex A as inspected.
  10. Select B next; it is closest to A according to the table.
  11. Explore distances from B to its uninspected neighbors.
  12. The neighboring vertices.
  13. Compute the distance from B to C: 4.
  14. With BC known, set AC to 9 (combine AB's 5 and BC's 4) and update the table.
  15. Compute the distance from B to E: 12.
  16. With BE known, set AE to 17 (combine AB's 5 and BE's 12) and update the table.
  17. Mark vertex B as inspected.
  18. Inspect D next; it has the shortest distance from A among uninspected vertices.
  19. Explore distances from D to its uninspected neighbors.
  20. Only the edge D → C leads to an uninspected vertex; B is already inspected.
  21. Compute the distance from D to C: 4.
  22. Since AC is 9, the alternative route via D to C (AD + DC = 8 + 4 = 12) is not shorter—make no update.
  23. Mark vertex D as inspected.
  24. Inspect C next; it has the shortest distance from A among uninspected vertices.
  25. Explore distances from C to its uninspected neighbors.
  26. The neighboring vertices.
  27. Compute the distance from C to E: 2.
  28. Shorten AE to 11 via CE (add AC's 9 and CE's 2) and update the table.
  29. Compute the distance from C to F: 15.
  30. With CF known, set AF to 24 (combine AC's 9 and CF's 15) and update the table.
  31. Mark vertex C as inspected.
  32. Inspect E next; it has the shortest distance from A among uninspected vertices.
  33. Explore distances from E to its uninspected neighbors.
  34. Only the edge E → F leads to an uninspected vertex; D is already inspected.
  35. Compute the distance from E to F: 7.
  36. Shorten AF to 18 via EF (add AE's 11 and EF's 7) and update the table.
  37. Mark vertex E as inspected.
  38. Inspect F next; it has the shortest distance from A among uninspected vertices.
  39. Inspect F, the last uninspected vertex.
  40. Vertex F has no reachable neighbors.
  41. Mark vertex F as inspected.
  42. The table provides the shortest paths from the source to all vertices. As an example, use it to obtain the shortest path from A to F.
  43. Vertex E is identified as the predecessor of F.
  44. Vertex C is identified as the predecessor of E.
  45. Vertex B is identified as the predecessor of C.
  46. Vertex A is identified as the predecessor of B.
  47. Draw the shortest path from A to F.
  48. The shortest path from A to F has been successfully drawn.
  49. The shortest path from A to F, A → B → C → E → F, weighs 5 + 4 + 2 + 7 = 18. The table gives the distances from A: B 5, C 9, D 8, E 11 and F 18.
Dijkstra's algorithm on a directed graph. Last step: The shortest path from A to F, A → B → C → E → F, weighs 5 + 4 + 2 + 7 = 18. The table gives the distances from A: B 5, C 9, D 8, E 11 and F 18.

When does Dijkstra's algorithm fail?

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.

Why Dijkstra's algorithm fails with negative weights

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.

Dijkstra's algorithm time and space complexity

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 queueTake smallestUpdateTotal time
Plain arrayO(V)O(1)O(V2)
Binary heapO(log V)O(log V)O((V + E) log V)
Fibonacci heapO(log V) amortizedO(1) amortizedO(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).

Dijkstra vs BFS, Bellman-Ford and A*

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.

DijkstraBFSBellman-Ford
TimeO((V + E) log V)O(V + E)O(V·E)

Dijkstra's algorithm in Python, Java and C++

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++.

Applications of Dijkstra's algorithm

  • Network routing: OSPF (RFC 2328) and IS-IS (RFC 1195) routers run Dijkstra's algorithm on their map of the network to build a shortest-path tree.
  • Maps and GPS: route planners for whole continents run faster methods built on Dijkstra, such as A*, bidirectional search and contraction hierarchies. Google has not published the details of its routing engine.
  • Interview problems: in LeetCode 743, Network Delay Time, the answer is the largest distance in the table, or −1 if any vertex stays at ∞.

From A to F here.
Any two vertices 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.

Four graphs from A to F

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.

Shortest path on a graph you draw

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.

How it works, where it fails

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.

Python, Java and C++

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.

Quiz

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.

Shortest paths and spanning trees

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.

Shortest paths,
closest vertex first.

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