Sub topic 8
Recovering the Actual Shortest Paths
The heap-based implementation from the previous chapter returns two dictionaries: dist and prev. Most of the time dist gets the attention, but a navigation app, a network router, or a game AI usually needs the route itself, not only its cost. This chapter shows how the prev dictionary encodes every shortest path at once, how to read paths out of it, and which edge cases break naive reconstruction code.
It assumes you have read the earlier chapters on edge relaxation and the heapq implementation, and that you are comfortable with Python dictionaries and loops.
The Predecessor Map
A predecessor map is a dictionary that stores, for each reached vertex v, the vertex u from which the current best distance to v was achieved. In the implementation, the map is updated in exactly one place: the line that performs a successful relaxation.
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 # remember which edge produced this distance
heapq.heappush(heap, (nd, v))
return dist, prevThe key rule is that dist[v] and prev[v] always change together. Whenever dist[v] holds a value, prev[v] names the vertex whose edge produced that value. Because the two are updated in the same branch, they can never get out of sync.
The source is the one reached vertex that has no entry in prev. Leaving it out is deliberate, and reconstruction code relies on it.
Why prev[v] is final once v is popped
During the run, prev[v] may be overwritten several times as better routes to v turn up. Once v is popped and added to visited, the greedy invariant guarantees that dist[v] is the true shortest distance. No later relaxation can satisfy nd < dist[v], so prev[v] never changes again either. When the loop ends, every reached vertex has a final predecessor.
Lazy deletion does not interfere. A stale heap entry for v carries an old, larger distance, and the visited check skips it before any relaxation happens. Stale entries never touch prev.
Watching prev Change
Take a small graph in which the direct edges are traps:
| Step | Popped (d, u) | Relaxations that succeed | prev after step |
|---|---|---|---|
| 1 | (0, A) | B: 4 via A, C: 1 via A | B→A, C→A |
| 2 | (1, C) | B: 3 via C, D: 6 via C | B→C, C→A, D→C |
| 3 | (3, B) | D: 4 via B | B→C, C→A, D→B |
| 4 | (4, B) | none, stale entry skipped | unchanged |
| 5 | (4, D) | none, D has no out-edges | unchanged |
| 6 | (6, D) | none, stale entry skipped | unchanged |
prev["B"] started as A and was overwritten to C. prev["D"] went from C to B. Each overwrite happened at the same moment the distance improved.
Walking Backwards to the Source
The predecessor map points backwards: from each vertex toward the source. To recover a path, you start at the target, follow prev until you reach the source, and then reverse the list.
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(prev) # {'B': 'C', 'C': 'A',
print(reconstruct_path(prev, "A", "D")) # ['A', 'C', 'B', 'D']
print(reconstruct_path(prev, "A",A']Appending and then reversing once costs O(L), where L is the number of vertices on the path. Inserting at the front of a on every step (path.insert(0, x)) would cost O(L²). For long paths, collections.deque.appendleft is an alternative that avoids the reversal.
Edge cases the guard handles
| Situation | What happens |
|---|---|
| `target == source` | Loop body never runs; returns `[source]` |
| Target unreachable | Target is not in `prev`; returns `None` |
| Target not in the graph at all | Same as unreachable; returns `None` |
| Target reachable | Loop ends when it reaches the source, the only reached vertex without a predecessor |
Return None for "no path" instead of an empty list. An empty list is easy to confuse with a valid but trivial result, and None forces the caller to handle the case explicitly.
The Shortest-Path Tree
Every reached vertex except the source has exactly one predecessor, and following predecessors always leads back to the source. That structure is a tree rooted at the source, called the shortest-path tree. The prev map stores the tree's edges in child-to-parent form, using O(V) space, yet it encodes a shortest path to every reachable vertex.
This explains why a single run of Dijkstra answers shortest-path queries to every target: you pay for the search once, and each later path query costs only O(L).
To traverse the tree top-down, for example to print it or to find all vertices whose route passes through a given hub, invert prev into a children map:
def shortest_path_tree(prev):
children = {}
for v, u in prev.items():
children.setdefault(u, []).append(v)
return children
print(shortest_path_tree(prev)) # {'C': ['B'], 'A': ['C'], 'B': ['D']}Paths with Costs Along the Way
Users often want the cumulative cost at each step, for example "arrive at C after 1, at B after 3". You don't need to store anything extra, because dist already holds the shortest distance to every vertex on the path.
def path_with_costs(dist, prev, source, target):
path = reconstruct_path(prev, source, target)
if path is None:
return None
return [(v, dist[v]) for v in path]
print(path_with_costs(dist, prev, "A", "D"))
# [('A', 0), ('C', 1), ('B', 3), ('D', 4)]This works because every prefix of a shortest path is itself a shortest path. The cost of reaching an intermediate vertex along the tree is exactly that vertex's dist.
Checking a Predecessor Map
A bug in relaxation code often shows up as a prev that disagrees with dist, for example if prev[v] = u is placed outside the if branch. The tree property gives a cheap check: for every entry, the parent's distance plus the edge weight must equal the child's distance.
def check_predecessors(graph, dist, prev):
for v, u in prev.items():
# min() handles parallel edges between the same pair of vertices
w = min(wt for nbr, wt in graph[u] if nbr == v)
assert dist[v] == dist[u] + w, f"bad tree edge {u} -> {v}"
return True
print(check_predecessors(graph, dist, prev)) # TrueThis check runs in O(E) time and is a good assertion to add in tests. With floating-point weights, compare with math.isclose instead of ==.
Ties: When More Than One Shortest Path Exists
The strict comparison nd < dist[v] keeps the first route found at the minimum cost and ignores later routes that only tie it. That gives one valid shortest path per vertex, which is usually what you want. Which of the tied paths you get depends on heap order and adjacency-list order, so don't write tests that expect one particular tied path.
If you need all shortest paths, for example for counting routes or for load balancing, store a list of predecessors and append on ties:
import heapq
def dijkstra_all_preds(graph, source):
dist = {source: 0}
preds = {source: []}
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
preds[v] = [u]
heapq.heappush(heap, (nd, v))
elif nd == dist[v]:
preds[v].append(u) # equally short; no new heap entry needed
return dist, preds
def all_shortest_paths(preds, source, target):
if target == source:
yield [source]
return
for p in preds.get(target, []):
for path in all_shortest_paths(preds, source, p):
yield path + [target]
g = {"S": [("A", 1), ("B", 1)], "A": [("T", 1)], "B": [("T", 1)], "T": []}
dist2, preds = dijkstra_all_preds(g, "S")
print(list(all_shortest_paths(preds, "S", "T")))
# [['S', 'A', 'T'], ['S', 'B', 'T']]With multiple predecessors the structure is no longer a tree. It is a directed acyclic graph (DAG) of shortest paths, as long as all weights are positive.
Undirected Graphs
Nothing changes for undirected graphs as long as the adjacency list stores each edge in both directions. The prev map still points toward the source. A common mistake is storing an undirected edge only once, which silently makes some routes impossible and makes reconstruction return None for vertices that should be reachable.
Exercise
A colleague moves the line prev[v] = u so that it runs for every neighbor examined, before the if-check. Using the example graph with edges A→B (4), A→C (1), C→B (2), C→D (5), B→D (1), what does prev["B"] end up as, and what path does reconstruct_path return for D?
Show answer
Every examination now overwrites prev. B is examined from A, then from C. Each examination overwrites prev["B"], so it ends as C, which happens to be correct. D is examined from C and then from B, so prev["D"] ends as B. This graph hides the bug and still yields ['A', 'C', 'B', 'D']. In general the bug records the last vertex to examine v rather than the one that improved it. Add edge D→B (10): when D is popped it examines B and sets prev["B"] = D. That creates a B→D→B cycle and reconstruction loops forever. check_predecessors would also catch it, since 4 + 10 ≠ 3.
Exercise
Why does reconstruct_path test "target not in prev" instead of "target not in dist" to detect an unreachable target, and would the other test also work?
Show answer
Both work for targets other than the source, because dist and prev gain entries together during relaxation. A vertex is in dist if and only if it is in prev, except for the source, which is in dist but has no predecessor. Testing prev with the extra target != source condition needs only one dictionary, so the function does not need dist as a parameter.
Exercise
You run Dijkstra once from a warehouse and then need routes to 10,000 delivery addresses. What is the total cost of the reconstruction step, and how does it compare with running Dijkstra per address?
Show answer
Each reconstruction costs O(L) for a path of L vertices, so the total is the sum of the path lengths, at most O(10,000 · V) and usually far less. Running Dijkstra per address would cost 10,000 · O((V + E) log V). One run plus tree lookups is far cheaper because the shortest-path tree already stores every route from the warehouse.