Sub topic 7
Implementing Dijkstra's Algorithm with heapq
This chapter turns the hand-traced algorithm into working Python. It assumes you already know edge relaxation, the greedy rule of expanding the closest unvisited vertex, and how a binary heap supports push and pop-min in O(log n) time. It also assumes you can read Python dicts, lists and tuples.
The Working Model
Python's heapq module keeps a plain list in min-heap order. heapq.heappush(heap, item) adds an item, and heapq.heappop(heap) removes and returns the smallest one. Each heap item is a tuple (distance, vertex). Tuples compare by their first element, so the item with the smallest tentative distance comes out first.
heapq has no operation to lower the priority of an item already in the heap. The standard workaround is lazy deletion. When relaxation finds a shorter distance to a vertex, you push a new entry and leave the old one in the heap. When an outdated (stale) entry is popped later, you recognize it and skip it.
The Implementation
import heapq
def dijkstra(graph, source):
"""graph: dict mapping node -> list of (neighbor, weight), weights >= 0."""
dist = {source: 0}
prev = {}
heap = [(0, source)]
visited = set()
while heap:
d, u = heapq.heappop(heap)
if u in visited:
continue # stale entry left by lazy deletion
visited.add(u)
for v, w in graph.get(u, []):
nd = d + w
if v not in dist or nd < dist[v]:
dist[v] = nd
prev[v] = u
heapq.heappush(heap, (nd, v))
return dist, prev
graph = {
"A": [("B", 4), ("C", 1)],
"C": [("B", 2), ("D", 5)],
"B": [("D", 1)],
"D": [],
}
dist, prev = dijkstra(graph, "A")
print(dist) # {'A': 0, 'B': 3, 'C': 1, 'D': 4}
print(prev) # {'B': 'C', 'C': 'A', 'D': 'B'}Each piece has one job:
distholds the best distance found so far. A vertex missing from it has not been reached yet, which stands in for infinity.visitedholds the finalized vertices. Once a vertex is popped and visited, its distance cannot improve.prevrecords which vertex gave each distance its latest improvement. The next chapter uses it to rebuild paths.graph.get(u, [])handles vertices that appear only as edge targets and have no adjacency list of their own.
Watching the Heap
The table shows what happens to the heap on the example graph.
| Pop | Action | Heap after |
|---|---|---|
| (0, A) | visit A, push B=4, C=1 | (1,C), (4,B) |
| (1, C) | visit C, push B=3, D=6 | (3,B), (4,B), (6,D) |
| (3, B) | visit B, push D=4 | (4,B), (4,D), (6,D) |
| (4, B) | stale, skip | (4,D), (6,D) |
| (4, D) | visit D, no edges | (6,D) |
| (6, D) | stale, skip | empty |
The heap held two stale entries. Because every push matches one successful relaxation, the heap never holds more than E + 1 entries, where E is the number of edges.
Common Errors
- Forgetting the stale check. Without
if u in visited: continue, the loop re-expands vertices. The answers stay correct with non-negative weights, but the extra work can grow large. - Putting the vertex first in the tuple.
(vertex, distance)orders the heap by name, which breaks the greedy rule. - Uncomparable vertices. When two distances tie, Python compares the vertices next. Strings and integers compare fine, but custom objects or dicts raise
TypeError. Use(d, counter, v)with an increasing counter to break ties safely. - Initializing every distance to infinity and pushing all vertices. This works, but it makes the heap bigger than it needs to be and gains nothing with lazy deletion.
Exercise
In the example run, vertex D is pushed twice, as (6, D) and then (4, D). Why does the code still report dist["D"] == 4, and what happens when (6, D) is popped?
Show answer
The heap pops (4, D) first because 4 < 6. At that point D is added to visited and dist["D"] is already 4. When (6, D) is popped later, D is in visited, so the continue statement skips it without relaxing any edges.
Exercise
Change the graph so that edge C to B has weight 5 instead of 2. Without running the code, what are dist and prev?
Show answer
A to C costs 1 and A to B costs 4. C to B now costs 1 + 5 = 6, which is worse than 4, so B keeps distance 4 with prev B = A. D is reached through C at 6 or through B at 4 + 1 = 5, so D = 5 with prev D = B. The result is dist = {'A': 0, 'B': 4, 'C': 1, 'D': 5} and prev = {'B': 'A', 'C': 'A', 'D': 'B'}.