Sub topic 12
Dijkstra's algorithm with lazy deletion
This chapter assumes you know Python lists, tuples and dictionaries, how heapq works, and what a weighted graph is. Dijkstra's algorithm finds the shortest distance from one source node to every other node. It requires all edge weights to be zero or positive.
The idea
Dijkstra's algorithm keeps a tentative distance for each node. It repeatedly takes the unfinished node with the smallest tentative distance, which is exactly what a min-heap returns. That node's distance is now final, because no other route can be shorter when all weights are non-negative. The algorithm then checks each outgoing edge and lowers a neighbor's distance if the new route is shorter.
The problem is that heapq has no decrease-key operation. It cannot find an item inside the heap and lower its priority. Lazy deletion works around this. When you find a shorter path to a node, you push a new entry with the smaller distance and leave the old entry in the heap. When an old entry is popped later, you detect that it is out of date and skip it.
The code
import heapq
def dijkstra(graph, source):
# graph: dict mapping every node to a list of (neighbor, weight) pairs, weights >= 0
dist = {source: 0}
heap = [(0, source)]
while heap:
d, u = heapq.heappop(heap)
if d > dist.get(u, float("inf")):
continue # stale entry left by an earlier, longer path
for v, w in graph[u]:
nd = d + w
if nd < dist.get(v, float("inf")):
dist[v] = nd
heapq.heappush(heap, (nd, v))
return dist
g = {"a": [("b", 1), ("c", 4)], "b": [("c", 2)], "c": []}
print(dijkstra(g, "a")) # {'a': 0, 'b': 1, 'c': 3}The dist dictionary holds the best known distance for each node. Nodes that are not in it have not been reached yet, so dist.get(u, float("inf")) treats them as infinitely far away.
Tracing the example
- Start with
dist = {a: 0}and heap[(0, a)]. - Pop
(0, a). Edge a→b gives 1, so push(1, b). Edge a→c gives 4, so push(4, c). - Pop
(1, b). Edge b→c gives 1 + 2 = 3, which beats 4. Setdist[c] = 3and push(3, c). The entry(4, c)is still in the heap. - Pop
(3, c). It matchesdist[c], so it is current. Node c has no outgoing edges. - Pop
(4, c). Now4 > dist[c], which is 3, so the entry is stale and the loop skips it.
Cost
Each edge can cause at most one push, so the heap never holds more than E entries, where E is the number of edges. Every push and pop costs O(log E). The total time is O(E log E), which is the same as O(E log V) because E is at most V². Memory is O(V + E) in the worst case. Stale entries use extra space, but they add no asymptotic cost.
Common errors
- Skipping the stale check. Without the
d > dist[u]test, the algorithm still gives correct distances. It reprocesses outdated entries, though, and can do far more work on dense graphs. - Negative weights. A node's distance is only final when it is popped if no later edge can reduce it. A negative edge breaks that rule, so the result can be wrong. Use Bellman-Ford instead.
- Missing graph keys. The code reads
graph[u]for every reached node, so each node must appear as a key, even with an empty list, as"c"does above. Usegraph.get(u, [])if that is not guaranteed. - Unorderable nodes. If two entries have equal distances, Python compares the node values. Nodes that cannot be compared, such as dictionaries, raise
TypeError. Add a counter as a tie-breaker, as shown in the earlier chapter on tie-breaking.
Exercise
A graph has edges a→b (weight 5), a→c (weight 1) and c→b (weight 1). In what order are the entries pushed and popped, and which entry is skipped as stale?
Show answer
Pop (0, a), then push (5, b) and (1, c). Pop (1, c), then push (2, b) because 1 + 1 = 2 beats 5. Pop (2, b), which is current. Pop (5, b), which is stale because 5 > dist[b] = 2, so it is skipped. Final distances are a: 0, c: 1, b: 2.