Dijkstra's algorithm: finding the shortest path

When every edge in a graph has its own length, this finds the shortest path from one start node to every other node. Press "Next" and watch the nodes get fixed one by one, closest first.

Short answer. Dijkstra's algorithm fixes the closest node that is not fixed yet, then shortens the distance to each of its neighbors if the new way is shorter. It repeats this until every node is fixed. If every edge length is 0 or more, a detour through other nodes can never make the closest node any closer, so it is safe to fix it. With a heap to pull out the closest node quickly, it takes time in proportion to E log V even in the worst case, for E edges and V nodes.

NodeABCDEF

Press "Next" to move one step. There are 25 steps in all: one step to fix a node, one step for each edge leaving that node, and one last step that follows the path back. A node filled green is fixed, and it stays green on later steps. The orange ring marks the current node. The orange arrow is the edge being checked, with its sum, and a gray arrow is an edge to a node that is already fixed (skipped). A crossed-out number is the distance before the update. Thick green edges link each node to its previous node, and at the end they form the shortest-paths tree. Orange cells in the table are the values changed on this step. On the last step, blue arrows lead back from the chosen destination to the start. The graph is made up, and every edge can be used in both directions.

Try this. 1. On step 2, B gets distance 4 from the direct edge out of A. On step 4, C (distance 2) is fixed, and on step 6 the edge C → B drops B to 3 (through C, 2 + 1). The direct edge is not always the shortest way. 2. D goes ∞ → 10 → 8, E goes ∞ → 12 → 10, and F goes ∞ → 14 → 13. 3. At the end (step 25), the shortest path from A to F is A → C → B → D → E → F, length 13. Set the destination to E and you get A → C → B → D → E, length 10.

Definitions

The text below explains in plain words. These are the textbook definitions. In a graph G = (V, E), s is the start node. When we write running time, V and E stand for the number of nodes and edges.

weight, path weight
A weighted graph has a real number w(u, v) on each edge (u, v). The length w(p) of a path p=v0,v1,…,vk is the sum of the weights of the edges it uses.

w(p)=∑i=1kw(vi−1,vi)

shortest path
Among the paths from s to v, one with the smallest length w(p). Its length is the shortest distance δ(s, v), and it is ∞ when there is no path from s to v. If a negative cycle (a cycle whose weights add up to a negative number) can be reached from s, nodes reached through that cycle have no shortest path. Finding shortest paths from one node s to every node is the single-source shortest paths problem.

δ(s,v)=min{w(p)∣p is a path from s to v}

relaxation
An operation on one edge (u, v). If going to v through u is shorter than dist[v], the shortest distance to v known so far, it lowers dist[v] to that length and sets the previous node (predecessor) of v to u.

dist[v]←min(dist[v], dist[u]+w(u,v))

Dijkstra's algorithm
An algorithm for single-source shortest paths in a graph where every weight is 0 or more. Set dist[s] = 0 and dist of every other node to ∞. Then repeat: among the nodes not yet final, make the one u with the smallest dist final, and relax every edge leaving u. When u is made final, dist[u] = δ(s, u). If a priority queue (heap) gives the smallest node, the worst case takes O(E log V) time.

w(u,v)≥0(∀(u,v)∈E)

shortest-paths tree
A tree with root s made of, for each node reachable from s, the edge from its previous node to it. The one path from s to v in this tree is a shortest path from s to v.

1. The problem: edges with different lengths

A picture made of nodes (points) and edges (lines) is called a graph. Each edge has a length. We want the shortest path from one start node to every other node. The length of a path is the sum of the lengths of the edges on it.

If every edge has the same length, you only need to count edges, and breadth-first search solves it. When lengths differ, a path with fewer edges can be longer. In the lab, A → B is one edge (4), but A → C → B is two edges and only 3.

The answer keeps two things for each node: the shortest distance known so far, and the previous node on that path. Follow the previous nodes back from the destination to the start and you get the whole path.

2. The idea: fix the closest node first

Trying every path gets out of hand fast, because the number of paths grows very quickly as nodes are added. Dijkstra's algorithm does this instead.

  1. Set the start node's distance to 0 and every other node to ∞ (not known yet).
  2. Among the nodes not fixed yet, pick the node u with the smallest distance and fix it.
  3. For each edge leaving u, if going through u is shorter, update that neighbor v: its distance, and its previous node (u).
  4. Repeat 2 and 3 until no node is left unfixed, or every node left has distance ∞.

Here is the update in step 3 as a formula. Books call it relaxation (see the sources).

dist[v] = min(dist[v], dist[u] + w(u, v))
Before 5 B D dist 3 · fixed dist 10 previous: C After: check edge B → D 3 + 5 = 8 B D dist 3 · fixed dist 10 → 8 8 < 10 → update previous: B
Checking one edge. This is step 3 of the "Follow it by hand" table below (step 12 in the lab). B is fixed at distance 3, and the edge B–D has length 5, so going through B gives 8. That is smaller than the 10 that D had, so D's distance becomes 8 and its previous node becomes B. In the formula above, min(10, 3 + 5) = 8.

Why fixing is safe. Say u has the smallest distance d among the nodes not fixed yet. Take any other path from the start to u. At some point it reaches its first node that is not fixed yet; call it x. Every node before x is fixed, and their edges already updated x, so the path up to x is at least x's distance, and x's distance is at least d. The rest of the path from x to u has edge lengths of 0 or more, so the total cannot drop below d. That is why u's distance will never change again. This argument leans on "every edge length is 0 or more".

PropertyWhat it means
A fixed distance never changes againOnly when every edge length is 0 or more. So if you need just one destination, you can stop when it is fixed
One start, every node, in one runYou get each node's distance and previous node together
The previous nodes form a treeThe shortest paths from the start to every node fit in one tree. The green edges in the lab
It can be wrong with negative lengthsSection 4

3. Follow it by hand

Here is the lab's graph traced to the end. Each cell shows the distance known so far, with the previous node in brackets. ✓ means fixed, and bold means the value changed on that step. One step in this table groups the lab's step that fixes a node with the steps that check its edges one by one.

StepFixedABCDEFWhy
Start−0∞∞∞∞∞The start is 0 away. No way to the other nodes is known yet
1A (0)✓ 04 (A)2 (A)∞∞∞Closest node: A (0). B: 0 + 4 = 4 < ∞, C: 0 + 2 = 2 < ∞
2C (2)✓ 03 (C)✓ 210 (C)12 (C)∞Closest node: C (2). B: 2 + 1 = 3 < 4, D: 2 + 8 = 10 < ∞, E: 2 + 10 = 12 < ∞
3B (3)✓ 0✓ 3✓ 28 (B)12 (C)∞Closest node: B (3). D: 3 + 5 = 8 < 10
4D (8)✓ 0✓ 3✓ 2✓ 810 (D)14 (D)Closest node: D (8). E: 8 + 2 = 10 < 12, F: 8 + 6 = 14 < ∞
5E (10)✓ 0✓ 3✓ 2✓ 8✓ 1013 (E)Closest node: E (10). F: 10 + 3 = 13 < 14
6F (13)✓ 0✓ 3✓ 2✓ 8✓ 10✓ 13Only F (13) is left. Its neighbors are all fixed, so nothing changes

On step 3, fixing B shortens D from 10 (through C) to 3 + 5 = 8 (through B). After the last step, follow the previous nodes back from F: F ← E ← D ← B ← C ← A. Turn it around and you get A → C → B → D → E → F, length 2 + 1 + 5 + 2 + 3 = 13.

4. Why it breaks with negative lengths

If an edge can be negative, a path that comes back through a node fixed later can be shorter. The "rest of the path is 0 or more" part of section 2 no longer holds. The graph below has four one-way edges (arrows), and B → A is −3. If a two-way edge were negative, you could go back and forth on it forever and the length would keep dropping, so there would be no shortest path. That is why this example uses one-way edges.

NodeDijkstra's answerTrue shortest distanceRight?

The "true shortest distance" comes from a function that tries every path starting at S. With only 4 nodes, trying them all is easy. The orange edge is the negative one.

Try this. Dijkstra fixes S(0) → A(2) → C(3) → B(4), in that order. The true shortest distances are 1 for A (S → B → A: 4 − 3) and 2 for C (S → B → A → C). When it fixed A at distance 2, it could not know that a path through B (distance 4, not fixed yet) would turn out shorter. "A fixed distance never changes" broke, and C, which is reached through A, came out wrong too.

The book in the sources says there are two versions of Dijkstra's algorithm. The version that puts each node on the priority queue only once (like the lab and the code on this page, which never look at a fixed node again) is guaranteed to take E log V time, but it can be wrong with negative edges. The version that lets a node go on the queue more than once is right as long as there is no negative loop, but its running time can grow exponentially in the worst case. That is why the book's code stops with an error when it sees a negative edge. With negative edges, use Bellman-Ford (section 6).

5. Pulling out the closest node fast: a heap

Every step needs "the node with the smallest distance among those not fixed yet". With V nodes, scanning all of them on each step, for V steps, is V × V scans just for that. If you keep (distance, node) pairs in a heap, the smallest one is always at the front, so you can pull it out without scanning everything. The book in the sources says Dijkstra's algorithm with a priority queue takes time in proportion to E log V and memory in proportion to V in the worst case.

In plain words: twice the edges takes about twice the time, and twice the nodes only adds as much as log V growing by 1. In Python, the standard library's heapq is a heap. The smallest item sits at heap[0], and the one line heapq.heappop(heap) takes it out (see the sources).

import heapq
def dijkstra(graph, start):
    dist, prev, done = {start: 0}, {start: None}, set()
    heap = [(0, start)]
    while heap:
        d, u = heapq.heappop(heap)           # the closest node not fixed yet
        if u in done: continue               # an old record of a node already fixed
        done.add(u)                          # fix it
        for v, w in graph[u]:
            if v not in done and d + w < dist.get(v, float("inf")):
                dist[v], prev[v] = d + w, u  # shorter, so update
                heapq.heappush(heap, (d + w, v))
    return dist, prev
graph = {"S": [("A", 2), ("B", 4)], "A": [("C", 1)], "B": [("A", -3)], "C": []}
print(dijkstra(graph, "S")[0])   # {'S': 0, 'A': 2, 'B': 4, 'C': 3}: A and C are wrong, as in section 4

This code pushes a new record each time a distance gets shorter, and throws away old records when it pops them (if u in done). So the heap can hold as many records as there are edges, and memory grows with E. Feed it the lab's graph with each edge in both directions and you get {'A': 0, 'B': 3, 'C': 2, 'D': 8, 'E': 10, 'F': 13}.

6. When to use what

MethodUse it whenTime (worst case)Extra memoryGoodBad
Breadth-first searchEvery edge has the same lengthIn proportion to V + E. It looks at each node and edge onceVSimplest, just one queueWrong when lengths differ
Dijkstra (heap)Lengths differ and are all 0 or moreE log V. Twice the edges, about twice the timeV (E if you push a node more than once, like the code above)Fast. Can stop once the destination is fixedCan be wrong with negative lengths
Bellman-FordSome lengths are negativeE × V. Twice the nodes and twice the edges, four times the timeVRight with negative lengthsSlow. No shortest path if there is a negative loop

The best and typical cases depend on the shape of the graph, so they are not listed. The time and memory for Dijkstra and Bellman-Ford are the values given in the book in the sources.

Where it is used

Common questions

If I only need one destination, do I have to run it to the end?

No. Once the destination is fixed, its distance never changes again, so you can stop right there. In the lab, E is the fifth node fixed (distance 10) and never changes after that.

Can I use Dijkstra when every edge has the same length?

You get the right answer. But then the order of distance is just the order of how many edges you cross, so breadth-first search, which needs only a plain queue and no heap, is simpler and faster.

What do I use when there are negative edges?

Use Bellman-Ford. With E edges and V nodes it takes time in proportion to E × V, so it is slower than Dijkstra, but it is right with negative edges. If there is a loop whose lengths add up to a negative number, going around it again always makes the path shorter, so there is no shortest path at all.

Words

Word used hereTextbook term
nodevertex
edge lengthedge weight
graph of one-way edgesdirected graph, digraph
shortest paths from one start to every nodesingle-source shortest paths
shortest distance known so fardistance estimate (distTo[v], dist[v])
previous nodepredecessor (edgeTo[v])
update if shorterrelaxation
tree made of previous nodesshortest-paths tree
structure that pulls out the smallest item fastpriority queue, heap
loop whose lengths add up to a negative numbernegative cycle

Sources

← Topological sortMinimum spanning trees →