Dijkstra's algorithm with a heap
🌍 In real life. Pour water into a dry riverbed at stop A, and let it spread along the roads at one road-kilometre per minute. The water reaches each place at the moment equal to its shortest distance from A, and the places it reaches first are exactly the closest ones. Dijkstra's algorithm is that flood, run in order of arrival.
The idea in one sentence: keep a frontier of best-known distances in a heap; again and again take the closest place not yet settled, call its distance final, and see whether its roads give any neighbour a shorter distance.
Its words:
- settle: declare a place's distance final; Dijkstra settles places in order of distance
- frontier: the places reached but not yet settled, with their best-known distances, kept in a heap of
(distance, place) - relax an edge: for a road v → w costing c, if
dist[v] + cbeatsdist[w], lowerdist[w] - stale entry: an old, bigger
(distance, place)still in the heap after a shorter one was pushed; skip it when it comes out
Step by step:
dist = {start: 0}, and the heap holds(0, start)- pop the smallest
(d, v); ifvis already settled, skip it - settle
v; for each roadv → wwith costc, ifd + cis shorter thanw's best so far, record it and push(d + c, w) - repeat until the heap is empty
Watch the frontier on the bus map. B is first reached for 4 taka, then more cheaply for 3 through C, so the old (4, B) becomes stale and is skipped later:
Why the closest unsettled place is final. Say v comes out of the heap with distance d, the smallest in the frontier. Any other route from the start to v must leave the settled places at some point, through some place u in the frontier, and getting to u already costs at least d (nothing in the frontier is closer). Every road costs 0 or more, so the rest of that route can only add. So no route to v is cheaper than d, and d is final. This needs non-negative weights; Lesson 54.3 shows what breaks without them.
What it costs, by counting. Every place is settled once, and every road is relaxed at most once from each end; each push and pop on the heap costs about log₂ of its size (Chapter 49). That gives O((V + E) log V). For 10,000 stops and 50,000 roads that is about 60,000 × 14 ≈ 840,000 steps. The simple version without a heap scans every stop to find the closest, V times: 10,000 × 10,000 = 100,000,000 steps.
import heapq
def dijkstra(graph, start):
dist = {start: 0}
heap = [(0, start)]
done = set()
while heap:
d, v = heapq.heappop(heap) # the closest place not settled yet
if v in done:
continue # a stale, bigger entry: skip it
done.add(v) # its distance is final now
for w, cost in graph[v]:
nd = d + cost
if w not in dist or nd < dist[w]:
dist[w] = nd # a shorter way to w
heapq.heappush(heap, (nd, w))
return dist
bus = {"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)]}
for stop, fare in sorted(dijkstra(bus, "A").items()):
print(stop, fare)Getting the route, not just the fare. Remember, for each place, the place its best distance came from (prev). When the search is done, walk prev back from the goal to the start and reverse the list:
import heapq
def cheapest_path(graph, a, b):
dist, prev = {a: 0}, {}
heap, done = [(0, a)], set()
while heap:
d, v = heapq.heappop(heap)
if v in done:
continue
done.add(v)
for w, cost in graph[v]:
nd = d + cost
if w not in dist or nd < dist[w]:
dist[w] = nd
prev[w] = v # remember the road it came by
heapq.heappush(heap, (nd, w))
if b not in dist:
return (None, [])
path = [b]
while path[-1] != a:
path.append(prev[path[-1]])
return (dist[b], path[::-1])
bus = {"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)]}
print(cheapest_path(bus, "A", "F"))Mistakes and edge cases.
- a plain queue instead of a heap: then places come out in the order they were found, not by distance, and a settled distance can still be wrong
- not skipping stale entries: a place can come out of the heap several times; without the
donecheck it is settled again from an old, bigger distance - stopping as soon as the goal is pushed: a cheaper road may still reach it; the goal's distance is final only when it is popped
- negative weights: the proof above needs costs of 0 or more (Lesson 54.3)
- unreachable places: they never enter
dist; report them as unreachable rather than looking them up
Quiz
What does this print?
import heapq def dijkstra(graph, start): dist = {start: 0} heap = [(0, start)] done = set() while heap: d, v = heapq.heappop(heap) # the closest place not settled yet if v in done: continue # a stale, bigger entry: skip it done.add(v) # its distance is final now for w, cost in graph[v]: nd = d + cost if w not in dist or nd < dist[w]: dist[w] = nd # a shorter way to w heapq.heappush(heap, (nd, w)) return dist g = {"A": [("B", 5), ("C", 1)], "B": [("A", 5), ("C", 2)], "C": [("A", 1), ("B", 2)]} print(dijkstra(g, "A"))When is a place's distance final in Dijkstra's algorithm?
- When it is popped from the heap as the closest unsettled place
- When it is first pushed onto the heap
- When all its neighbours are pushed
What does this print?
import heapq def cheapest_path(graph, a, b): dist, prev = {a: 0}, {} heap, done = [(0, a)], set() while heap: d, v = heapq.heappop(heap) if v in done: continue done.add(v) for w, cost in graph[v]: nd = d + cost if w not in dist or nd < dist[w]: dist[w] = nd prev[w] = v # remember the road it came by heapq.heappush(heap, (nd, w)) if b not in dist: return (None, []) path = [b] while path[-1] != a: path.append(prev[path[-1]]) return (dist[b], path[::-1]) g = {"A": [("B", 1), ("C", 4)], "B": [("A", 1), ("C", 2)], "C": [("A", 4), ("B", 2)]} print(cheapest_path(g, "A", "C"))Why does the heap sometimes hold two entries for the same place?
- A shorter distance was found after the first was pushed; the old one is skipped when it comes out
- Every place is pushed twice on purpose
- It's a bug
This sometimes settles a place again from a stale, bigger distance. After which line is a check missing?
def dijkstra(graph, start): dist, heap, done = {start: 0}, [(0, start)], set() while heap: d, v = heapq.heappop(heap) done.add(v) for w, cost in graph[v]: if w not in dist or d + cost < dist[w]: dist[w] = d + cost heapq.heappush(heap, (d + cost, w)) return dist
Coding tasks
Write
dijkstra(graph, start): a dict from every place reachable fromstartto its cheapest distance.graphmaps each place to a list of(neighbour, cost)pairs; every cost is 0 or more.Write
cheapest_path(graph, a, b): return(cost, path), the cheapest cost fromatoband the list of places on that route, or(None, [])ifbcan't be reached. Remember a place's previous stop only when its distance gets strictly shorter.