Sub topic 9
Recovering Paths from Predecessors
This chapter assumes you have read the Bellman-Ford chapter and can follow its relaxation loop. You should also be comfortable with Python lists. Bellman-Ford returns distances, but often you need the route itself: which vertices to visit, and in what order.
What the predecessor array stores
Every time Bellman-Ford relaxes an edge (u, v, w) successfully, it records pred[v] = u. That entry means "the best path found so far to v arrives from u." When the algorithm finishes without finding a negative cycle, each reachable vertex points to the vertex before it on one shortest path. The source and every unreachable vertex keep None.
For the example graph from the Bellman-Ford chapter, the final arrays are:
| Vertex | `dist` | `pred` |
|---|---|---|
| 0 | 0 | None |
| 1 | 4 | 0 |
| 2 | 1 | 1 |
| 3 | 5 | 2 |
Vertex 2 first got pred[2] = 0 through the direct edge of weight 5. Relaxing (1, 2, -3) then overwrote it with 1. The array only keeps the latest improvement, and that is the one you want.
The predecessor tree
The pred pointers together form a tree rooted at the source, called the shortest-path tree. Each vertex has exactly one parent, so walking parent links from any vertex leads back to the source.
Walking backward
To rebuild a path, start at the target and follow pred until you reach None. This gives the path in reverse order, so reverse it at the end.
def reconstruct_path(pred, source, target):
if target != source and pred[target] is None:
return [] # target is unreachable
path = []
v = target
while v is not None:
path.append(v)
v = pred[v]
path.reverse()
return path
pred = [None, 0, 1, 2] # output of bellman_ford on the example graph
print(reconstruct_path(pred, 0, 3)) # [0, 1, 2, 3]
print(reconstruct_path(pred, 0, 0)) # [0]The first check handles unreachable targets. If you leave it out, an unreachable vertex returns [target], which looks like a valid one-vertex path. The source also has pred[source] is None, so the check excludes it explicitly.
The walk costs O(V) time, because a simple path visits at most V vertices. Appending and then reversing once is cheaper than inserting at the front of a list on every step.
Common errors
Other mistakes come up often:
- Pointing
predthe wrong way. Store the vertex you came from,pred[v] = u, and not the vertex you are going to. - Updating
predon ties. If you use<=instead of<, equal-cost relaxations keep overwritingpred. With zero-weight cycles this can create pointer loops. - Forgetting to reverse. The backward walk produces target-to-source order.
Exercise
A run of Bellman-Ford from source 0 on a 5-vertex graph produces pred = [None, 3, 0, 2, None]. What does reconstruct_path return for targets 1 and 4, and why?
Show answer
For target 1 the walk goes 1 -> 3 -> 2 -> 0 -> None, and reversing it gives [0, 2, 3, 1]. For target 4, pred[4] is None and 4 is not the source, so vertex 4 is unreachable and the function returns [].
Exercise
Modify the while loop so that it raises an error instead of looping forever when the pred pointers contain a cycle.
Show answer
Count the steps and raise once the count passes the number of vertices, because a simple path has at most len(pred) vertices. For example: add steps = 0 before the loop, and inside it write steps += 1, then if steps > len(pred): raise ValueError('cycle in predecessor pointers').