Sub topic 10
Thinking in Intermediate Vertices: The Floyd-Warshall Recurrence
This chapter assumes you know what edge relaxation is, how Bellman-Ford builds distances round by round, and the general idea of dynamic programming: solve a problem by combining answers to smaller versions of the same problem. Here we derive the recurrence behind Floyd-Warshall. The next chapter turns it into the standard compact implementation.
The All-Pairs Question Needs a Different Subproblem
Running Bellman-Ford once from each vertex answers the all-pairs question in O(V · VE) time. On a dense graph that becomes O(V^4). Floyd-Warshall gets O(V^3) by choosing a different way to make the problem smaller.
Bellman-Ford limits how many edges a path may use. Floyd-Warshall limits which vertices a path may pass through. An intermediate vertex of a path is any vertex on it other than the two endpoints. In the path 0 → 1 → 2 → 3, the intermediate vertices are 1 and 2.
Number the vertices 0 to n−1 and define:
- D_k[i][j] is the weight of the shortest path from i to j whose intermediate vertices all come from the set {0, 1, ..., k−1}.
D0 allows no intermediate vertices at all, so only direct edges count. Dn allows every vertex, so it holds the true shortest distances.
| Layer | Allowed intermediates | Meaning |
|---|---|---|
| D_0 | none | direct edges only (0 on the diagonal) |
| D_1 | {0} | paths that may pass through vertex 0 |
| D_2 | {0, 1} | paths that may pass through 0 and 1 |
| D_n | all vertices | true shortest distances |
Deriving the Recurrence
Suppose we know Dk and want D{k+1}. The new layer adds vertex k to the allowed set. Take a shortest i-to-j path P whose intermediates come from {0, ..., k}. There are only two cases.
- P does not pass through k. Then all its intermediates come from {0, ..., k−1}, and its weight is D_k[i][j].
- P passes through k. If there are no negative cycles, a shortest path can be taken to be simple, so k appears exactly once. Split P at k. The part from i to k and the part from k to j each use only intermediates from {0, ..., k−1}, because k is now an endpoint of each part. Each part must also be shortest of its kind, or swapping in a shorter one would shorten P. So the weight is Dk[i][k] + Dk[k][j].
Taking the better of the two cases gives the recurrence:
- D{k+1}[i][j] = min( Dk[i][j], Dk[i][k] + Dk[k][j] )
The base case is D0[i][i] = 0, D0[i][j] = w(i, j) if an edge exists (the smallest weight if there are parallel edges), and ∞ otherwise.
The second term is a relaxation step. It treats the best i-to-k route and the best k-to-j route as if they were a single "edge" and asks whether going through k improves the i-to-j distance. Floyd-Warshall is relaxation applied to pairs of paths, not to single edges.
Watching the Layers Fill In
The code below builds every layer as a separate matrix so you can see the recurrence work. This uses O(V^3) memory and is meant for learning. The next chapter shows why a single matrix is enough.
import math
def fw_layers(n, edges):
D = [[math.inf] * n for _ in range(n)]
for i in range(n):
D[i][i] = 0
for u, v, w in edges:
D[u][v] = min(D[u][v], w)
layers = [D]
for k in range(n):
prev = layers[-1]
cur = [[min(prev[i][j], prev[i][k] + prev[k][j]) for j in range(n)]
for i in range(n)]
layers.append(cur)
return layers
def show(M):
for row in M:
print(" ".join(f"{x:>4}" if x != math.inf else " inf" for x in row))
edges = [(0, 1, 4), (0, 2, 5), (1, 2, -3), (2, 3, 4), (1, 3, 6)]
for k, M in enumerate(fw_layers(4, edges)):
print(f"D_{k}:")
show(M)Python handles math.inf + (-3) as inf, so missing paths never turn into false improvements. Tracing the graph by hand:
- D_0: row 0 is [0, 4, 5, ∞] and row 1 is [∞, 0, −3, 6].
- D_1 (allow 0): no edge enters vertex 0, so nothing can route through it. No change.
- D_2 (allow 1): D[0][2] becomes min(5, 4 + (−3)) = 1, and D[0][3] becomes min(∞, 4 + 6) = 10.
- D_3 (allow 2): D[0][3] becomes min(10, 1 + 4) = 5, and D[1][3] becomes min(6, −3 + 4) = 1.
- D_4 (allow 3): no edge leaves vertex 3. No change.
The final row 0 is [0, 4, 1, 5]. It matches what Bellman-Ford produced from source 0 earlier in the tutorial.
How This Differs from the Bellman-Ford Recurrence
Both algorithms are dynamic programs. They grow different parameters.
| Aspect | Bellman-Ford | Floyd-Warshall |
|---|---|---|
| Subproblem parameter | maximum number of edges | allowed set of intermediate vertices |
| Number of stages | V − 1 | V |
| Work per stage | relax every edge, O(E) | update every pair, O(V^2) |
| Answers | one source | all pairs |
| Total time | O(VE) | O(V^3) |
The Floyd-Warshall recurrence never looks at the edge list after initialization. Its cost depends only on V, which is why it suits dense graphs and does not gain anything on sparse ones.
Common Errors
Other mistakes that show up often:
- Forgetting the zero diagonal. If D[i][i] starts at ∞, paths that begin or end at the pivot vertex k never combine correctly, because D[k][k] takes part in the updates.
- Overwriting parallel edges. Assigning
D[u][v] = wfor every edge keeps the last weight, not the smallest. Usemin. - Using a finite "infinity" such as 109.** Adding two of them, or one plus a negative weight, can produce a value that beats a real path or overflows in fixed-width languages. Skip the update when D[i][k] is infinite, or use a true infinity.
- Assuming the recurrence holds with negative cycles. Case 2 relied on k appearing at most once. If a negative cycle exists, looping through it again keeps lowering the cost, so "shortest" has no finite value. The recurrence still runs, and its diagonal reveals the problem, which a later chapter covers.
Exercise
Using the example graph, compute D2[1][3] and D3[1][3]. Explain which allowed intermediate vertex causes the change.
Show answer
D2[1][3] = 6. Allowing vertices 0 and 1 gives no better route from 1 to 3 than the direct edge, since nothing enters 0 and 1 is the start. D3[1][3] = min(6, D2[1][2] + D2[2][3]) = min(6, -3 + 4) = 1. Allowing vertex 2 as an intermediate causes the change.
Exercise
Case 2 of the derivation assumes a shortest path visits k at most once. Give a small graph where this fails and explain what goes wrong.
Show answer
Take edges 0 -> 1 (weight 1), 1 -> 2 (weight -2), 2 -> 1 (weight 1), and 1 -> 3 (weight 1). The cycle 1 -> 2 -> 1 has weight -1. A path from 0 to 3 can loop through vertex 1 any number of times, and each loop lowers the cost by 1, so no shortest path exists. Splitting at one visit of k no longer covers every path, so the recurrence's values stop meaning "shortest distance". D[1][1] also becomes negative, which signals the cycle.
Exercise
Why does the order i, j, k (with k innermost) give wrong answers, even though it evaluates the same min expression?
Show answer
With k innermost, D[i][j] is finalized after one sweep over k, using D[i][k] and D[k][j] values that may not yet include paths through higher-numbered vertices. The recurrence requires every pair to be complete for intermediates {0..k-1} before vertex k is added, and only an outermost k loop guarantees that.