Sub topic 13
All-Pairs Path Reconstruction with a Next-Hop Matrix
This chapter assumes you know the Floyd-Warshall triple loop from the previous chapters, how a predecessor array rebuilds a single-source path, and how a negative value on the diagonal of the distance matrix signals a negative cycle. The goal here is narrower: after Floyd-Warshall finishes, how do you get the actual route from any i to any j, and not only its length?
Why Distances Are Not Enough
A distance matrix tells a routing system that the cheapest route from 0 to 3 costs 5. It does not say which edges to take. You could store every shortest path explicitly, but there are V² pairs and each path can have up to V vertices, so that costs O(V³) memory. A next-hop matrix stores one vertex per pair, which is O(V²) memory, the same as the distance matrix. You can then rebuild any path in time proportional to its length.
The definition:
nxt[i][j]is the first vertex afterion a shortest path fromitoj.nxt[i][i] = i.nxt[i][j] = Nonewhenjcannot be reached fromi.
Initialization and the Update Rule
Before the main loop, the only known paths are single edges. For each edge (u, v, w) that is the cheapest edge between u and v, set nxt[u][v] = v. When there are parallel edges, keep the next hop that goes with the smallest weight.
Inside the loop, Floyd-Warshall finds that going through k is cheaper:
dist[i][k] + dist[k][j] < dist[i][j]The new best path is i ⇝ k ⇝ j. Its first step is the first step of the i ⇝ k part, so the update is:
nxt[i][j] = nxt[i][k]The k ⇝ j part needs no record here. It is already encoded in row k and in the rows of the vertices after it. Each row only knows the next step, and following the next steps one after another rebuilds the whole path.
Tracing the Example
Use the tutorial's running graph: edges (0,1,4), (0,2,5), (1,2,-3), (2,3,4), (1,3,6).
| Phase | Change to dist | Change to nxt |
|---|---|---|
| Init | edges copied | `nxt[0][1]=1`, `nxt[0][2]=2`, `nxt[1][2]=2`, `nxt[1][3]=3`, `nxt[2][3]=3` |
| k = 0 | none (no edges enter 0) | none |
| k = 1 | `dist[0][2]`: 5 → 1 | `nxt[0][2] = nxt[0][1] = 1` |
| k = 1 | `dist[0][3]`: ∞ → 10 | `nxt[0][3] = nxt[0][1] = 1` |
| k = 2 | `dist[0][3]`: 10 → 5 | `nxt[0][3] = nxt[0][2] = 1` |
| k = 2 | `dist[1][3]`: 6 → 1 | `nxt[1][3] = nxt[1][2] = 2` |
| k = 3 | none (no edges leave 3) | none |
At k = 2 the route from 0 to 3 changes from 0→1→3 to 0→1→2→3, but nxt[0][3] stays 1. The first hop did not change. The change shows up in row 1, where nxt[1][3] became 2. This is why the scheme works: improvements further along a path get recorded in the rows of the vertices where they happen.
Final next-hop matrix (— means unreachable):
| from \ to | 0 | 1 | 2 | 3 |
|---|---|---|---|---|
| 0 | 0 | 1 | 1 | 1 |
| 1 | — | 1 | 2 | 2 |
| 2 | — | — | 2 | 3 |
| 3 | — | — | — | 3 |
The whole walk stays in column j. To rebuild a path to j, you only read nxt[*][j].
A Safe Reconstruction Routine
The plain walker from the Floyd-Warshall chapter assumes there is no negative cycle. If a negative cycle lies on some walk from i to j, then dist[i][j] is really −∞. The next-hop entries along that walk may point around the cycle, so the walk either never stops or returns a path whose weight does not match dist[i][j]. A pair (i, j) is affected exactly when some vertex k is reachable from i, can reach j, and has dist[k][k] < 0. The version below checks that condition first and also caps the walk at V vertices as a safety net.
import math
def floyd_warshall(n, edges):
dist = [[math.inf] * n for _ in range(n)]
nxt = [[None] * n for _ in range(n)]
for i in range(n):
dist[i][i] = 0
nxt[i][i] = i
for u, v, w in edges:
if w < dist[u][v]:
dist[u][v] = w
nxt[u][v] = v
for k in range(n):
for i in range(n):
if dist[i][k] == math.inf:
continue
for j in range(n):
if dist[i][k] + dist[k][j] < dist[i][j]:
dist[i][j] = dist[i][k] + dist[k][j]
nxt[i][j] = nxt[i][k]
return dist, nxt
def touches_negative_cycle(dist, i, j):
n = len(dist)
return any(dist[i][k] < math.inf and dist[k][j] < math.inf and dist[k][k] < 0
for k in range(n))
def fw_path_safe(dist, nxt, i, j):
if nxt[i][j] is None:
return [] # unreachable
if touches_negative_cycle(dist, i, j):
raise ValueError(f'no shortest path {i} -> {j}: negative cycle')
path = [i]
while i != j:
i = nxt[i][j]
path.append(i)
if len(path) > len(nxt): # a simple path has at most n vertices
raise ValueError('next-hop table contains a loop')
return path
edges = [(0, 1, 4), (0, 2, 5), (1, 2, -3), (2, 3, 4), (1, 3, 6)]
dist, nxt = floyd_warshall(4, edges)
for i in range(4):
for j in range(4):
p = fw_path_safe(dist, nxt, i, j)
if i != j and p:
print(f'{i} -> {j}: {p} (weight {dist[i][j]})')
# 0 -> 1: [0, 1] (weight 4)
# 0 -> 2: [0, 1, 2] (weight 1)
# 0 -> 3: [0, 1, 2, 3] (weight 5)
# 1 -> 2: [1, 2] (weight -3)
# 1 -> 3: [1, 2, 3] (weight 1)
# 2 -> 3: [2, 3] (weight 4)
bad = [(0, 1, 1), (1, 2, -1), (2, 1, -1), (2, 3, 1)]
dist, nxt = floyd_warshall(4, bad)
try:
fw_path_safe(dist, nxt, 0, 3)
except ValueError as e:
print(e) # no shortest path 0 -> 3: negative cycleCalling touches_negative_cycle costs O(V) per query. If you answer many queries, precompute a boolean matrix of affected pairs once in O(V³), or mark them by setting dist[i][j] = -math.inf.
Next-Hop vs. Predecessor Matrix
You can store the last vertex before j instead of the first vertex after i. That is a predecessor matrix pred[i][j], with initialization pred[u][v] = u and update pred[i][j] = pred[k][j]. Each row of it is a Bellman-Ford-style predecessor array for source i.
| Aspect | Next-hop `nxt[i][j]` | Predecessor `pred[i][j]` |
|---|---|---|
| Update rule | `nxt[i][k]` | `pred[k][j]` |
| Walk direction | forward from `i` | backward from `j`, then reverse |
| Column/row read during walk | column `j` | row `i` |
| Natural fit | routing tables: each node keeps only its own row | reuse of single-source code per row |
| Memory | O(V²) | O(V²) |
Both give correct paths. Pick next-hop when consumers move forward step by step, as packets do in a network. Pick predecessor when you already have tooling for single-source predecessor arrays.
Gotchas
- Strict comparison. Use
<, not<=. With zero-weight cycles,<=can overwrite a valid next hop with an equally cheap one that points back around the cycle, and the walker then loops. - Infinity sentinels. Python's
math.inf + (-3)is stillinf, soinf + w < infis false. In languages that use a large integer such asINF = 10**9,INF + (-3) < INFis true and creates bogus next hops into unreachable vertices. Skip the update when either half isINF, as thecontinueabove does fordist[i][k]. Also checkdist[k][j]if you use a sentinel. - Parallel edges. Initialize from the cheapest edge only. Otherwise
nxtcan point along an edge whose weight is not the one indist. - Negative self-loops. An edge
(v, v, w)withw < 0setsdist[v][v] = wduring initialization. The detection check handles this correctly, andnxt[v][v]staysv. - Mutating after the fact. If you change one edge weight, the whole
nxttable can become stale. Floyd-Warshall has no cheap incremental update, so you need to rerun it.
Exercise
In the traced example, why did nxt[0][3] stay 1 when the shortest 0-to-3 path changed from 0→1→3 to 0→1→2→3 at k = 2?
Show answer
The update sets nxt[0][3] = nxt[0][2], and nxt[0][2] was already 1 from k = 1. Both routes start with the edge 0→1, so the first hop is unchanged. The change in the rest of the route is recorded in row 1, where nxt[1][3] became 2.
Exercise
Add the edge (0, 3, 2) to the example graph and rerun Floyd-Warshall. What are dist[0][3], nxt[0][3], and the reconstructed path?
Show answer
dist[0][3] = 2, nxt[0][3] = 3, and the path is [0, 3]. Initialization sets nxt[0][3] = 3 with weight 2. No route through 1 or 2 costs less than 2 (the best is 5), so the entry never changes.
Exercise
Write the initialization and update rule for a predecessor matrix pred[i][j], and explain why the update reads row k rather than row i.
Show answer
Initialize pred[i][i] = i and pred[u][v] = u for each cheapest edge (u, v). When going through k improves (i, j), set pred[i][j] = pred[k][j]. The new path is i ⇝ k ⇝ j, and its last edge belongs to the k ⇝ j part, so the vertex before j is the predecessor recorded for the pair (k, j).
Exercise
An implementation uses INF = 10**9 and no skip checks. The graph has an edge (2, 3, -5) and vertex 2 is unreachable from 0. What can go wrong in nxt[0][3]?
Show answer
At k = 2, dist[0][2] + dist[2][3] = 109 - 5, which is less than dist[0][3] = 109 if 3 is otherwise unreachable. The update sets a finite-looking distance and nxt[0][3] = nxt[0][2] = None, so a reachable-looking pair has no next hop, or a real path's next hop gets corrupted. The fix is to skip the update whenever dist[i][k] or dist[k][j] equals INF.