Sub topic 10
Thinking in Intermediate Vertices: The Floyd-Warshall Recurrence
This chapter assumes you know what edge relaxation is, what a negative cycle is, and the basic idea of dynamic programming: you solve a problem by building it up from smaller subproblems whose answers you store. Here we derive the recurrence behind Floyd-Warshall. The next chapter turns it into the usual triple loop.
The subproblem: restrict the intermediate vertices
Bellman-Ford makes its subproblems smaller by limiting how many edges a path may use. Floyd-Warshall limits something else: which vertices a path may pass through.
Number the vertices 0..n-1. An intermediate vertex of a path is any vertex on it other than the two endpoints. Define:
d_k(i, j)is the weight of the shortest path fromitojwhose intermediate vertices all come from{0, 1, ..., k-1}.
When k = 0, no intermediate vertex is allowed, so d_0(i, j) is just the direct edge weight. It is 0 when i == j and infinity when no edge exists. When k = n, every vertex is allowed, so d_n(i, j) is the true shortest distance.
The recurrence
Moving from k-1 to k adds exactly one new allowed vertex, m = k-1. Every shortest path that may use m falls into one of two cases:
- The path does not use
m. Its length isd_{k-1}(i, j). - The path uses
m. It splits into a piece fromitomand a piece frommtoj. Neither piece usesmas an intermediate vertex, so their lengths ared_{k-1}(i, m)andd_{k-1}(m, j).
So:
d_k(i, j) = min(d_{k-1}(i, j), d_{k-1}(i, m) + d_{k-1}(m, j))
This is a relaxation step in which the "edge" is a whole subpath through m.
The recurrence as code
The memoized function below follows the definition directly. It is slow and only meant to make the recurrence concrete. It uses the same graph as the earlier chapters.
import math
from functools import lru_cache
edges = [(0, 1, 4), (0, 2, 5), (1, 2, -3), (2, 3, 4), (1, 3, 6)]
n = 4
w = [[math.inf] * n for _ in range(n)]
for i in range(n):
w[i][i] = 0
for u, v, c in edges:
w[u][v] = min(w[u][v], c)
@lru_cache(maxsize=None)
def d(k, i, j):
# shortest i->j path using only vertices 0..k-1 as intermediates
if k == 0:
return w[i][j]
m = k - 1
return min(d(k - 1, i, j), d(k - 1, i, m) + d(k - 1, m, j))
for k in range(n + 1):
print(k, d(k, 0, 3))Output:
0 inf
1 inf
2 10
3 5
4 5The distance improves only when it becomes legal to pass through a vertex the best path needs. Allowing vertex 1 finds 0 -> 1 -> 3 with weight 10. Allowing vertex 2 as well finds 0 -> 1 -> 2 -> 3 with weight 5.
Common errors
- Wrong loop order. Each layer
kdepends only on layerk-1, sokmust be the outermost loop. Ifkis placed inside theiorjloops, the code reads values that have not been finalized yet, and the results can be wrong. - Bad base case. Forgetting
d_0(i, i) = 0, or keeping a heavier parallel edge instead of the lighter one, corrupts every later layer. - Worrying about memory too early. Storing every layer looks like it needs O(n³) space. Row
mand columnmdo not change during roundk, so one matrix updated in place is enough. The next chapter relies on this.
Exercise
Using the example graph, what is d_2(0, 2), the shortest 0-to-2 distance when only vertices 0 and 1 may be intermediates? Which path achieves it?
Show answer
d2(0, 2) = min(d1(0, 2), d1(0, 1) + d1(1, 2)) = min(5, 4 + (-3)) = 1, achieved by the path 0 -> 1 -> 2.
Exercise
Why does the recurrence assume the path through m visits m only once, and what condition on the graph guarantees this?
Show answer
If a shortest path visited m twice, the part between the two visits would be a cycle. Removing that cycle would not make the path longer unless the cycle's weight is negative. So when the graph has no negative cycle, some shortest path is simple and visits m at most once.