Sub topic 8
Recovering the Actual Shortest Paths
This chapter assumes you have read the previous chapter's heap-based dijkstra function. It also assumes you are comfortable with Python dictionaries and lists. So far the algorithm tells you how far each vertex is from the source. Most real uses also need the route itself: the turns a navigation app gives you, or the hops a packet takes. This chapter shows how to recover that route at almost no extra cost.
The predecessor map
The fix is to record, for each vertex, which vertex it was reached from on the best route found so far. This record is called the predecessor map, prev. Whenever a relaxation lowers dist[v] through u, the code also sets prev[v] = u. The two updates always happen together, so prev[v] always points along the route that produced the current dist[v].
A predecessor can change during the run. In the example below, B is first reached directly from A with cost 4, so prev["B"] becomes "A". Later the route through C gives cost 3, and prev["B"] is overwritten with "C". Once B is popped from the heap, both values are final.
Walking backwards
The map stores each step back toward the source, so you rebuild a path by starting at the target and following prev until you reach the source. Then you reverse the list.
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
def reconstruct_path(prev, source, target):
if target != source and target not in prev:
return None # target unreachable
path = [target]
while path[-1] != source:
path.append(prev[path[-1]])
path.reverse()
return path
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(reconstruct_path(prev, "A", "D")) # ['A', 'C', 'B', 'D']Two edge cases need care:
- Target equals source. The source has no entry in
prev, so the guard checkstarget != sourcefirst. The result is["A"]. - Unreachable target. A vertex that was never relaxed has no
preventry, so the function returnsNone. Without the guard, the loop would raise aKeyError.
Each step in the walk costs O(1), so rebuilding a path with k edges takes O(k) time. The map itself adds O(V) memory.
The shortest-path tree
Every reachable vertex except the source has exactly one predecessor, and following predecessors always ends at the source. So the prev edges form a tree rooted at the source, called the shortest-path tree. One run of Dijkstra therefore gives you the shortest path to every reachable vertex, and you rebuild each one only when you need it.
| Common mistake | Symptom | Fix |
|---|---|---|
| Forgetting to reverse | Path prints target-first | Call `path.reverse()` |
| No reachability check | `KeyError` on unreachable target | Check `target in prev` first |
| Setting `prev` outside the improvement branch | Path cost differs from `dist[target]` | Assign `prev` only when `dist` improves |
Exercise
Using the example graph, what does the prev dictionary contain after dijkstra(graph, "A") finishes, and what does reconstruct_path(prev, "A", "B") return?
Show answer
prev is {'B': 'C', 'C': 'A', 'D': 'B'}. B was first given predecessor A (cost 4), then overwritten with C when the cost 3 route was found. The path to B is ['A', 'C', 'B'].
Exercise
Suppose you change the relaxation test to nd <= dist[v]. Are the distances still correct? Can the reconstructed paths change?
Show answer
The distances stay correct, because equal costs never lower dist. On ties, prev is overwritten with the later predecessor, so a different path of the same cost may be returned. Every path still has the shortest cost, but the extra heap pushes add work.