Sub topic 9
Recovering Paths from Predecessors
Distances alone often aren't enough. A routing table has to know which link to use next, and a navigation app has to draw the route. This chapter shows how the pred array that Bellman-Ford fills in becomes a full path. It covers the edge cases that break naive code, and it shows how to pull the negative cycle itself out of the same array.
This chapter assumes you have read the earlier chapters on edge relaxation and the Bellman-Ford algorithm. You should be comfortable with Python lists and with tracing loops by hand.
What the predecessor array records
Each time Bellman-Ford relaxes an edge (u, v, w) successfully, it sets dist[v] = dist[u] + w and pred[v] = u. The predecessor entry means "the best route to v found so far arrives from u." Bellman-Ford only overwrites pred[v] when it finds a strictly shorter route, so the final value belongs to the final distance.
Take the running example with edges (0,1,4), (0,2,5), (1,2,-3), (2,3,4) and (1,3,6), and source 0. The first pass sets pred[2] = 0 and then overwrites it with pred[2] = 1 when the negative edge gives a shorter route. The second pass changes nothing. The final state is:
| Vertex | dist | pred | Tight edge |
|---|---|---|---|
| 0 | 0 | None | (source) |
| 1 | 4 | 0 | 0 + 4 = 4 |
| 2 | 1 | 1 | 4 + (-3) = 1 |
| 3 | 5 | 2 | 1 + 4 = 5 |
Every non-source row satisfies dist[v] == dist[pred[v]] + w(pred[v], v). That edge is called tight. When the algorithm finishes with no reachable negative cycle, this equality holds for every reachable vertex. Bellman-Ford makes the edge tight when it sets the pointer. If dist[pred[v]] later dropped, that edge would be relaxed again and dist[v] would drop with it. Once no edge can be relaxed, the equality is exact.
The predecessor subgraph is a tree
Take the edges pred[v] -> v for every reachable vertex. When no negative cycle is reachable, these edges form a tree rooted at the source, called the shortest-path tree. Each vertex has exactly one parent, and the parent pointers never loop. Following them always ends at the source.
The tree stores one shortest path to every vertex in O(V) space. Storing each path as a list would cost O(V²) space in the worst case, for example on a long chain, and copying those lists on every relaxation would also cost time.
Walking the pointers back
To rebuild the path to target, start at target, follow pred until you reach None, then reverse the list:
import math
def bellman_ford(n, edges, source):
dist = [math.inf] * n
pred = [None] * n
dist[source] = 0
for _ in range(n - 1):
changed = False
for u, v, w in edges:
if dist[u] + w < dist[v]:
dist[v] = dist[u] + w
pred[v] = u
changed = True
if not changed:
break
for u, v, w in edges:
if dist[u] + w < dist[v]:
raise ValueError('negative cycle reachable from source')
return dist, pred
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
edges = [(0, 1, 4), (0, 2, 5), (1, 2, -3), (2, 3, 4), (1, 3, 6)]
dist, pred = bellman_ford(4, edges, 0)
print(dist) # [0, 4, 1, 5]
print(reconstruct_path(pred, 0, 3)) # [0, 1, 2, 3]
print(reconstruct_path(pred, 0, 0)) # [0]The walk takes O(L) time, where L is the number of edges on the path. L is at most V − 1.
Edge cases that break naive code
Unreachable targets
An unreachable vertex keeps pred = None and dist = inf. Without the early check, the loop would return [target], which looks like a valid one-vertex path. Check for unreachability first. You can test pred[target] is None as above, or test dist[target] == math.inf, which says the same thing more directly.
The source itself
The source has pred = None but is reachable. That is why the check is target != source and .... The correct path from the source to itself is [source] with weight 0.
Ties between equal-weight paths
If two paths have the same weight, the strict < keeps whichever one was found first. Which one that is depends on the order of the edge list. Both answers are correct. If your tests compare exact paths, they can fail after an unrelated change reorders the edges, so compare path weights instead.
Pointers taken before the algorithm finished
If you stop Bellman-Ford early, or read pred before the final pass, the pointers can describe a route that is not tight. They can even form a cycle. The tree guarantee only holds after convergence with no negative cycle.
Extracting the negative cycle
The loop that breaks path reconstruction is useful in its own right. When a negative cycle is reachable, the predecessor graph contains it. To recover it:
- Run n relaxation passes and record the last vertex
xrelaxed in the final pass. - Follow
predfromxn times. Every vertex relaxed in pass n has a predecessor chain that leads back into a negative cycle, so n steps are guaranteed to land on the cycle. - Walk around the cycle from that vertex until you return to it.
import math
def find_negative_cycle(n, edges, source):
dist = [math.inf] * n
pred = [None] * n
dist[source] = 0
x = None
for _ in range(n):
x = None
for u, v, w in edges:
if dist[u] + w < dist[v]:
dist[v] = dist[u] + w
pred[v] = u
x = v
if x is None:
return [] # no negative cycle reachable from source
for _ in range(n):
x = pred[x]
cycle = [x]
v = pred[x]
while v != x:
cycle.append(v)
v = pred[v]
cycle.append(x)
cycle.reverse()
return cycle
edges = [(0, 1, 1), (1, 2, -1), (2, 3, -1), (3, 1, -1)]
print(find_negative_cycle(4, edges, 0)) # [3, 1, 2, 3]The output lists the cycle in edge order, 3 → 1 → 2 → 3, with total weight −3. The starting vertex depends on edge order, but the cycle is the same. The arbitrage chapter uses this function to report which trades make up a profitable loop.
Cost summary
| Operation | Time | Extra space |
|---|---|---|
| Maintaining `pred` during Bellman-Ford | O(1) per relaxation | O(V) |
| Rebuilding one path | O(L), at most O(V) | O(L) |
| Rebuilding paths to all vertices | O(V²) worst case | O(V²) if all are stored |
| Extracting a negative cycle | O(VE) for the passes, O(V) for the walk | O(V) |
Exercises
Exercise
In the example graph, add the edge (3, 2, -1) and keep source 0. What happens when you call bellmanford, and what happens if you skip the final check and call reconstructpath(pred, 0, 3)?
Show answer
Edges 2 -> 3 (weight 4) and 3 -> 2 (weight -1) form a cycle of weight 3, which is positive, so there is no negative cycle. bellman_ford returns dist [0, 4, 1, 5] and the path is still [0, 1, 2, 3]. Relaxing 3 -> 2 would give 5 - 1 = 4, which is not less than 1, so pred[2] stays 1 and the pointers stay acyclic.
Exercise
A colleague writes while pred[v] is not None: path.append(v); v = pred[v] and then appends the source at the end. Which input makes this return a wrong answer?
Show answer
An unreachable target. pred[target] is None, so the loop never runs and the function returns [source], a path that doesn't exist. It also returns [source] when target == source, which is correct, so the bug only shows on unreachable vertices. Check dist[target] == math.inf first.
Exercise
Why does findnegativecycle step back n times from x before collecting the cycle, instead of starting the collection at x directly?
Show answer
x was relaxed in the last pass, but x may only be reachable from the cycle without lying on it, for example a vertex hanging off the cycle. Its predecessor chain leads into the cycle, and the chain has fewer than n vertices, so after n steps the walk must be on the cycle. Collecting from x directly could loop forever, because the walk might never return to x.