Sub topic 7
Implementing Dijkstra's Algorithm with heapq
This chapter turns the greedy rule and edge relaxation into working Python code. It assumes you have read the earlier chapters on relaxation, the greedy selection rule, and binary heaps. It also assumes you can read Python dicts, lists, tuples, and loops. The goal is an implementation that is short, correct, and safe on real inputs: graphs with dead-end vertices, unreachable vertices, ties in distance, and vertex types that Python cannot compare.
What the Implementation Has to Do
Each step of the algorithm needs one operation: "give me the unvisited vertex with the smallest tentative distance." Scanning every vertex for that minimum costs O(V) per step. A binary heap answers it in O(log V). Python's standard library provides a binary min-heap in the heapq module. The module works on a plain list and offers these functions:
| Function | Effect | Cost |
|---|---|---|
| `heapq.heappush(heap, item)` | Insert `item`, keeping the heap property | O(log n) |
| `heapq.heappop(heap)` | Remove and return the smallest item | O(log n) |
| `heapq.heapify(lst)` | Rearrange a list into a heap in place | O(n) |
| `heap[0]` | Look at the smallest item without removing it | O(1) |
heapq has no "decrease the priority of this item" operation. In Dijkstra's algorithm, a vertex's tentative distance can drop several times before the vertex is finalized. So the code needs some way to reflect each improvement.
Lazy Deletion: Push Again, Skip Later
The standard workaround is called lazy deletion. When a relaxation improves dist[v], the code does not touch the old heap entry for v. It pushes a new entry (new_distance, v) instead. The heap can then hold several entries for the same vertex. The smallest one always comes out first, because the heap is ordered by distance. The first time v is popped, its distance is final, and v is marked visited. Any later entry for v is stale, meaning it records a distance that has since been beaten. The loop discards stale entries when it pops them.
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, prevGoing through it line by line:
distholds tentative distances. It only contains vertices that have been reached, so it never needs a full vertex list up front. A vertex missing fromdisthas a distance of infinity.prevrecords, for each vertex, which vertex last improved it. The next chapter uses it to rebuild paths.heapstarts with the source at distance 0. Each entry is a tuple(distance, vertex), and Python compares tuples element by element, so the heap orders entries by distance first.- The
visitedcheck carries out lazy deletion. A vertex is finalized the first time it is popped, and later pops of it are ignored. graph.get(u, [])handles vertices that appear only as edge targets. A sink vertex such as"D"in the example below may have no key in the dict at all.- The relaxation test
v not in dist or nd < dist[v]stands in for comparing against infinity.
Running It and Watching the Heap
import heapq
def dijkstra(graph, source):
dist = {source: 0}
prev = {}
heap = [(0, source)]
visited = set()
while heap:
d, u = heapq.heappop(heap)
if u in visited:
continue
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'}The table below lists each pop in order, with the heap contents after that step's pushes. It matches the hand trace from the previous chapter, plus the stale entries that lazy deletion leaves behind.
| Pop | Action | Pushes | Heap after step |
|---|---|---|---|
| (0, A) | finalize A | (4, B), (1, C) | (1, C), (4, B) |
| (1, C) | finalize C; B improves 4 to 3 | (3, B), (6, D) | (3, B), (4, B), (6, D) |
| (3, B) | finalize B; D improves 6 to 4 | (4, D) | (4, B), (4, D), (6, D) |
| (4, B) | stale, skip | none | (4, D), (6, D) |
| (4, D) | finalize D | none | (6, D) |
| (6, D) | stale, skip | none | empty |
Each successful relaxation causes one push, so the heap holds at most E + 1 entries over the whole run. This is the extra memory lazy deletion costs. A later chapter on complexity looks at what it means for running time.
An Equivalent Stale Check
Some implementations leave out the visited set and compare the popped distance with the current best:
d, u = heapq.heappop(heap)
if d > dist[u]:
continue # a better entry for u was already processedThis works because dist[u] only ever goes down, and the entry that matches dist[u] comes out before any larger entry for u. The two checks behave the same on valid input. The visited set uses O(V) extra memory but states the intent clearly. The distance comparison uses no extra structure. There is one edge case: with zero-weight edges, two entries for u can have the same distance. The d > dist[u] check then lets both through, and u gets expanded twice. The result is still correct, because the second expansion improves nothing, but the work is wasted. The visited set never expands a vertex twice.
Tie-Breaking and Uncomparable Vertices
If two heap entries have the same distance, Python compares their second elements to order them. Strings and integers compare without trouble. Instances of a custom class without __lt__ do not:
import heapq
class Station:
def __init__(self, name):
self.name = name
s, a, b = Station("s"), Station("a"), Station("b")
heap = []
heapq.heappush(heap, (1, a))
try:
heapq.heappush(heap, (1, b)) # tie on distance, so a and b get compared
except TypeError as exc:
print("TypeError:", exc)The usual fix inserts a counter that increases with every push between the distance and the vertex. No two entries share a counter value, so Python never needs to compare vertices. Ties are also resolved in insertion order, which keeps results deterministic.
import heapq
from itertools import count
def dijkstra(graph, source):
"""Works for any hashable vertex type, comparable or not."""
dist = {source: 0}
prev = {}
tie = count()
heap = [(0, next(tie), source)]
visited = set()
while heap:
d, _, u = heapq.heappop(heap)
if u in visited:
continue
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, next(tie), v))
return dist, prev
class Station:
def __init__(self, name):
self.name = name
s, a, b = Station("s"), Station("a"), Station("b")
graph = {s: [(a, 1), (b, 1)], a: [(b, 1)]}
dist, _ = dijkstra(graph, s)
print({v.name: d for v, d in dist.items()}) # {'s': 0, 'a': 1, 'b': 1}Common Implementation Errors
| Mistake | Symptom | Fix |
|---|---|---|
| Pushing `(v, nd)` instead of `(nd, v)` | Vertices come out in name order, and distances are wrong | Put the priority first in the tuple |
| Changing `dist[v]` and expecting the heap entry to change | The heap never sees the new priority | Push a new entry; tuples in the heap are snapshots |
| Editing a list inside the heap in place | The heap property breaks silently | Never modify entries; push new ones |
| `graph[u]` instead of `graph.get(u, [])` | `KeyError` on sink vertices | Use `.get` or give every vertex a key |
| Marking visited when pushing, not when popping | Distances stay at the first value found, not the best | Finalize only on pop |
| Leaving out the stale check altogether | Still correct, but stale entries get relaxed again | Keep the `visited` or `d > dist[u]` check |
| Assuming every vertex is in `dist` | `KeyError` for unreachable vertices | Use `dist.get(v, math.inf)` |
The mistake of marking visited on push is the most common one, because it resembles breadth-first search, where marking on enqueue is correct. In BFS every edge has the same cost, so the first discovery of a vertex is also its shortest. With weighted edges, a vertex found first through a heavy edge can be reached more cheaply later, as B was in the trace above.
Handling Unreachable Vertices
A vertex that cannot be reached from the source never gets pushed, so it never appears in dist. That is useful: v in dist is a direct reachability test. If callers expect every vertex to have a value, fill in the missing ones at the boundary:
import math
def all_distances(graph, source):
dist, _ = dijkstra(graph, source)
vertices = set(graph) | {v for edges in graph.values() for v, _ in edges}
return {v: dist.get(v, math.inf) for v in vertices}This keeps the core loop simple. Infinity is added only where an interface needs it.
Exercise
In the trace table above, the heap pops (4, B) and (4, D), which have the same distance. Explain why (4, B) comes out first with the two-element tuple version, and say what decides the order in the counter version.
Show answer
In the two-element version, the distances tie, so Python compares the vertices as strings, and "B" < "D". In the counter version, the counter decides: (4, B) was pushed when A was expanded, before (4, D) was pushed when B was expanded, so (4, B) has the smaller counter and still comes out first. Either way it is stale and gets skipped.
Exercise
A colleague moves visited.add(v) into the relaxation branch, right after the push, and leaves out the visited check on pop. On the example graph, what distance does this report for B, and why?
Show answer
It reports 4. When A is expanded, B is pushed at distance 4 and marked visited at once. When C is expanded later, the path A-C-B costs 3, but B is already marked visited. If the relaxation test skips visited vertices, the improvement is never recorded. Finalizing on push treats the first distance found as the shortest, which only holds when all edges have equal weight.
Exercise
What is the largest number of entries the heap can hold over a full run on a graph with V vertices and E edges, and why?
Show answer
E + 1. The source is pushed once. Every other push comes from a successful relaxation of an edge (u, v), and each edge is relaxed at most once, because u is expanded only once. So there are at most E pushes besides the source.