Kodewick
Start learning →
Shortest paths: Dijkstra34 / 52

Shortest paths: Dijkstra

Lesson 34 of 52 · Part 6 · Graphs · about 18 minutes

Dijkstra's algorithm finds shortest paths when no edge weight is negative: heapq holds (distance, vertex) pairs, the closest unsettled vertex is popped and updates its neighbours, and old entries that come out stale are skipped.

A navigation app knows two routes from home to the office: one goes through only 2 junctions but is 9 km long; the other goes through 4 junctions and is only 6 km. BFS counts edges and would pick the first; what we want is the route whose weights add up to the least. That is the shortest path problem on a weighted graph, computed every day by road maps, network routing and game path-finding. Dijkstra's algorithm rests on a plain idea: the vertex closest to the start is the first whose distance can be settled; each time one is settled, use it to update its neighbours. With heapq handing over the closest one each time, it is a dozen lines of code, and a road network with a million edges takes the blink of an eye.

Settle the closest one each time

dist[v] holds "the shortest known distance from the start to v", and at first only dist[start] = 0. Then repeat:

  1. Among the vertices not yet settled, take the u with the smallest dist and settle it.
  2. For each edge u → v with weight w: if dist[u] + w is smaller than dist[v], update dist[v]. This step is called relaxing the edge.

Why can the smallest one be settled? All weights are ≥ 0, so a route through any other unsettled vertex already starts no shorter than dist[u], and adding non-negative edges only makes it longer.

Heap

From A: the number on a vertex is its current dist, green is settled, and the thick lines are the edges finally used (the shortest-path tree); the row below is the heap list itself, in its true order

Look at A → B: straight there is 4, round through C, two edges, is 3. The fewest edges is not always the shortest, which is why BFS can't be used here.

Choose one

Undirected graph: A–B 4, A–C 1, C–B 2, B–D 1, C–D 5. Running Dijkstra from A, in what order are the vertices settled?

Choose one

Same graph. Once C is settled and its neighbours relaxed, what are dist of B and D?

heapq hands over the closest

"Take the smallest dist each time" is a job for chapter 4's heap: put (distance, vertex) tuples in heapq; tuples compare by their first item first, so what pops is the smallest distance.

The snag: B went into the heap with 4, and later 3 was found. heapq can't change the value of an item inside the heap, nor delete one from the middle. The way round it is not to delete: push a new (3, B); the old (4, B) stays in the heap, and when it pops, 4 > dist[B] shows it is stale, so it is skipped. This is called lazy deletion.

PopAgainst distWhat happensLeft in the heap
(0, A)0 = dist[A]: validB gets 4, C gets 1, both pushed(1, C) (4, B)
(1, C)validB becomes 3, D gets 6, E gets 9(3, B) (4, B) (6, D) (9, E)
(3, B)validD becomes 4(4, B) (4, D) (6, D) (9, E)
(4, B)4 > 3: staleskipped(4, D) (9, E) (6, D)
(4, D)validE becomes 7(6, D) (9, E) (7, E)
(6, D)6 > 4: staleskipped(7, E) (9, E)
(7, E)validno neighbour gets shorter(9, E)
(9, E)9 > 7: staleskipped. The heap is empty: doneempty
The same graph, pop by pop: the old (4, B), (6, D) and (9, E) stay in the heap all along, and when they pop, one look at dist shows they are stale
main.py
1import heapq2 3graph = {4    "A": {"B": 4, "C": 1},5    "B": {"A": 4, "C": 2, "D": 1},6    "C": {"A": 1, "B": 2, "D": 5, "E": 8},7    "D": {"B": 1, "C": 5, "E": 3},8    "E": {"C": 8, "D": 3},9}10 11def dijkstra(graph, start):12    dist = {start: 0}13    heap = [(0, start)]14    pops = skipped = 015    while heap:16        d, u = heapq.heappop(heap)17        pops += 118        if d > dist[u]:                  # stale: u was already handled with a shorter distance19            skipped += 120            continue21        for v, w in graph[u].items():22            nd = d + w23            if v not in dist or nd < dist[v]:24                dist[v] = nd25                heapq.heappush(heap, (nd, v))26    return dist, pops, skipped27 28dist, pops, skipped = dijkstra(graph, "A")29print(dist)30print("popped", pops, "times, of which", skipped, "were stale and skipped")
Output
{'A': 0, 'B': 3, 'C': 1, 'D': 4, 'E': 7}
popped 8 times, of which 3 were stale and skipped

Each edge adds at most one item to the heap, so the heap holds at most e items, and each push or pop is O(log e). The total time is O((n + e) log n) (log e is at most 2 log n).

Don't leave out the line if d > dist[u]: continue. Without it the result is still right, but a stale vertex relaxes all its edges over again: as the graph grows, the wasted work grows along with the heap.

Guess the outputA wrong guess is fine

S to A directly is 5; round by B and C it is 1 + 1 + 1. What does it print?

1import heapq2 3graph = {"S": {"A": 5, "B": 1}, "B": {"C": 1}, "C": {"A": 1}, "A": {}}4dist = {"S": 0}5heap = [(0, "S")]6pops = 07while heap:8    d, u = heapq.heappop(heap)9    pops += 110    if d > dist[u]:11        continue12    for v, w in graph[u].items():13        if v not in dist or d + w < dist[v]:14            dist[v] = d + w15            heapq.heappush(heap, (d + w, v))16print(dist["A"], pops)
Put in orderDrag, or use the arrows

Put the three lines of each round in order: pop the closest, skip it if stale, relax its neighbours. relax(u, d) is already written: it uses u to update the neighbours and pushes any that got shorter.

  1. relax(u, d)
  2. if d > dist[u]: continue
  3. d, u = heapq.heappop(heap)
Should print
{'A': 0, 'B': 3, 'C': 1, 'D': 4, 'E': 7}
Choose one

B went into the heap as 4, and later a shorter 3 was found. With heapq, what do you usually do with the old (4, "B") still in the heap?

Exercise 1

Network delay time

Complete network_delay(times, n, k): n machines are numbered 1 to n, and (u, v, w) in times means a signal takes w milliseconds from u to v (directed). A signal starts at k; return how long until every machine has it (the shortest distance to the farthest machine), or -1 if some machine never gets it.

It should print
2
1
-1
3
exercise1.py
1import heapq2 3def network_delay(times, n, k):4    graph = {i: [] for i in range(1, n + 1)}5    for u, v, w in times:6        graph[u].append((v, w))7    dist = {k: 0}8    # Dijkstra: the heap holds (distance, machine), stale entries are skipped9    return -110 11print(network_delay([(2, 1, 1), (2, 3, 1), (3, 4, 1)], 4, 2))12print(network_delay([(1, 2, 1)], 2, 1))13print(network_delay([(1, 2, 1)], 2, 2))14print(network_delay([(1, 2, 4), (1, 3, 1), (3, 2, 1), (2, 4, 1)], 4, 1))
Output
Press Run or Ctrl+Enter

Negative edges make it wrong

Dijkstra relies on "the smallest value popped is the final answer", and that rests on no edge weight being negative. With a negative edge, a route that comes round later can turn out shorter, and what was "settled" earlier is wrong.

Heap

C → B weighs −2: B is settled first at 2, and only later does A → C → B turn out to be 3 − 2 = 1, but B is no longer changed
main.py
1import heapq2 3def dijkstra_done(graph, start):4    dist = {start: 0}5    done = set()                         # settled once popped, never changed again6    heap = [(0, start)]7    while heap:8        d, u = heapq.heappop(heap)9        if u in done:10            continue11        done.add(u)12        for v, w in graph[u].items():13            if v not in done and (v not in dist or d + w < dist[v]):14                dist[v] = d + w15                heapq.heappush(heap, (d + w, v))16    return dist17 18graph = {"A": {"B": 2, "C": 3}, "B": {"D": 1}, "C": {"B": -2}, "D": {}}19print("Dijkstra gives: ", dijkstra_done(graph, "A"))20print("really shortest:", {"A": 0, "B": 1, "C": 3, "D": 2})
Output
Dijkstra gives:  {'A': 0, 'B': 2, 'C': 3, 'D': 3}
really shortest: {'A': 0, 'B': 1, 'C': 3, 'D': 2}

The lazy-deletion version from the heapq stage would change B back on this small example, but only by luck: a vertex can be popped and relaxed again and again, taking exponential time in the worst case; and with a negative cycle, every lap round it is a little shorter, so it never stops. For negative edges, use Bellman-Ford (relax every edge for n − 1 rounds, O(n × e)), which can also detect a negative cycle.

Choose one

Directed edges 0 → 1 (1), 0 → 2 (3), 2 → 1 (−3). Starting from 0, what dist[1] does Dijkstra give, and what is the real shortest distance?

Choose one

Someone suggests adding 3 to every edge, so there are no negative weights, and then running Dijkstra. Why doesn't that work?

Rebuilding the path

dist only gives distances. To know the way, record prev[v] = u whenever dist[v] is updated: "the best route so far comes into v from u". At the end, walk back from the target along prev to the start, and reverse.

main.py
1import heapq2 3graph = {4    "A": {"B": 4, "C": 1},5    "B": {"A": 4, "C": 2, "D": 1},6    "C": {"A": 1, "B": 2, "D": 5, "E": 8},7    "D": {"B": 1, "C": 5, "E": 3},8    "E": {"C": 8, "D": 3},9}10 11def dijkstra(graph, start):12    dist = {start: 0}13    prev = {start: None}14    heap = [(0, start)]15    while heap:16        d, u = heapq.heappop(heap)17        if d > dist[u]:18            continue19        for v, w in graph[u].items():20            if v not in dist or d + w < dist[v]:21                dist[v] = d + w22                prev[v] = u              # note where this step came from23                heapq.heappush(heap, (d + w, v))24    return dist, prev25 26def path_to(prev, end):27    path = []28    while end is not None:29        path.append(end)30        end = prev[end]31    return path[::-1]32 33dist, prev = dijkstra(graph, "A")34print(prev)35for t in ["B", "D", "E"]:36    print(f"A to {t}: {dist[t]}", path_to(prev, t))
Output
{'A': None, 'B': 'C', 'C': 'A', 'D': 'B', 'E': 'D'}
A to B: 3 ['A', 'C', 'B']
A to D: 4 ['A', 'C', 'B', 'D']
A to E: 7 ['A', 'C', 'B', 'D', 'E']

The edges prev points along are the thick lines of the first figure: each vertex has one prev, and together they form a tree rooted at the start, the shortest-path tree.

Works forTime
BFSevery edge counts 1O(n + e)
Dijkstra + heapqweights ≥ 0O((n + e) log n)
Bellman-Fordnegative edges; finds negative cyclesO(n × e)
Dijkstra on a matrix (scan for the smallest each time)weights ≥ 0, dense graphsO(n²)

In interviews: "network delay time", "cheapest flights", "path with maximum probability" are all variations of Dijkstra. Make three points: the heap holds (distance, vertex); stale entries are skipped when they pop (lazy deletion); and why negative edges are not allowed. Asked for the complexity, answer O((n + e) log n).

Guess the outputA wrong guess is fine

prev is what Dijkstra recorded: "the last step came from here". What does this print?

1prev = {"A": None, "C": "A", "B": "C", "D": "B", "E": "D"}2path, end = [], "E"3while end is not None:4    path.append(end)5    end = prev[end]6print(path[::-1], len(path) - 1)
Choose one

n = 100,000 vertices, e = 200,000 edges, no negative weights; you want the shortest paths from one start to every vertex. What fits best?

Exercise 2

Distance and route

Complete route(graph, s, t): graph is a directed weighted graph as a dict of dicts; return (shortest distance, route as a list), or (-1, []) when t can't be reached. Rebuild the route with a prev dict.

It should print
(6, ['S', 'B', 'A', 'T'])
(8, ['B', 'C'])
(-1, [])
exercise2.py
1import heapq2 3def route(graph, s, t):4    dist = {s: 0}5    prev = {s: None}6    # Dijkstra, noting prev[v] = u whenever dist[v] is updated; at the end walk back from t along prev7    return -1, []8 9graph = {10    "S": {"A": 7, "B": 2},11    "A": {"T": 1},12    "B": {"A": 3, "C": 8},13    "C": {"T": 1},14    "T": {},15}16print(route(graph, "S", "T"))17print(route(graph, "B", "C"))18print(route(graph, "T", "S"))
Output
Press Run or Ctrl+Enter

How you write it at work

The standard library has no Dijkstra; heapq is the whole toolkit: heappush and heappop are both O(log n), it is a min-heap, and tuples compare by their first item. A few things from practice:

  • When distances tie, the tuples go on to compare the second item (the vertex). Strings and numbers compare fine; vertices that are objects of your own class can't be compared, so put a counter in between: (d, count, node).
  • For the distance to one target only: return the first time the target pops as valid; the rest need not be worked out.
  • A vertex that can't be reached is not in dist: use dist.get(v, math.inf).
  • On road networks with millions of vertices, industry adds an estimate (A*) or preprocessing on top of Dijkstra, but the core is still this one loop.
main.py
1import heapq2import math3 4def shortest(graph, s, t):5    dist = {s: 0}6    heap = [(0, s)]7    while heap:8        d, u = heapq.heappop(heap)9        if u == t:10            return d                     # the target's first pop is the answer11        if d > dist[u]:12            continue13        for v, w in graph.get(u, {}).items():14            if d + w < dist.get(v, math.inf):15                dist[v] = d + w16                heapq.heappush(heap, (d + w, v))17    return math.inf18 19flights = {"London": {"Paris": 900, "Rome": 1500}, "Paris": {"Rome": 500, "Athens": 1200},20           "Rome": {"Athens": 600}, "Athens": {}}21print(shortest(flights, "London", "Athens"))22print(shortest(flights, "Athens", "London"))
Output
2000
inf
Choose one

The vertices are objects of your own class (they can't be compared with <). You push the tuples (5, a) and (5, b) into heapq. What happens?

Summary

Take-away

Dijkstra: settle the closest one each time

  • Only for weights ≥ 0: the smallest distance popped is the final answer
  • heapq holds (distance, vertex); an update just pushes another, the old one stays
  • Popped with d > dist[u] means stale: skip it (lazy deletion)
  • Note prev[v] = u when dist[v] changes; walking back to the start gives the route
  • Time O((n + e) log n); with negative edges use Bellman-Ford
1heap = [(0, s)]; dist = {s: 0}2while heap:3    d, u = heapq.heappop(heap)4    if d > dist[u]: continue5    for v, w in graph[u].items():6        if d + w < dist.get(v, inf): dist[v] = d + w; heappush(heap, (d + w, v))