Sub topic 11
The Floyd-Warshall Algorithm
This chapter assumes you know the Floyd-Warshall recurrence from the previous chapter. It also assumes you can read nested Python loops and Big-O notation. Here we turn that recurrence into working code, trace it on a small graph, and cover the mistakes people make most often when implementing it.
From recurrence to three loops
The recurrence says that the best i-to-j path using only intermediate vertices from {0..k} either skips k or goes through it:
dist[i][j] = min(dist[i][j], dist[i][k] + dist[k][j])
The algorithm applies this update for each k in turn, and it applies it to every pair (i, j). A single 2D matrix is enough. You do not need a separate layer for each k. During round k, row k and column k never change, because dist[k][k] is 0. So updating the matrix in place reads the same values the layered version would read.
Implementation
import math
def floyd_warshall(n, edges):
# n vertices numbered 0..n-1; edges is a list of (u, v, w) tuples
dist = [[math.inf] * n for _ in range(n)]
for i in range(n):
dist[i][i] = 0
for u, v, w in edges:
if w < dist[u][v]: # keep the lightest of parallel edges
dist[u][v] = w
for k in range(n): # k must be the outermost loop
for i in range(n):
dik = dist[i][k]
if dik == math.inf: # i cannot reach k, so nothing to gain
continue
for j in range(n):
if dik + dist[k][j] < dist[i][j]:
dist[i][j] = dik + dist[k][j]
return dist
edges = [(0, 1, 4), (0, 2, 5), (1, 2, -3), (2, 3, 4), (1, 3, 6)]
for row in floyd_warshall(4, edges):
print(row)
# [0, 4, 1, 5]
# [inf, 0, -3, 1]
# [inf, inf, 0, 4]
# [inf, inf, inf, 0]The algorithm runs in O(V³) time and uses O(V²) space. Graph density does not change the cost, so Floyd-Warshall takes as long on a sparse graph as on a dense one.
Tracing the example
| Round k | Updates made |
|---|---|
| 0 | None, because no edge enters vertex 0 |
| 1 | `dist[0][2]`: 5 → 1 (via 1), `dist[0][3]`: inf → 10 (via 1) |
| 2 | `dist[0][3]`: 10 → 5 (via 2), `dist[1][3]`: 6 → 1 (via 2) |
| 3 | None, because vertex 3 has no outgoing edges |
The 0-to-3 distance improves twice. The first improvement comes when paths through vertex 1 become allowed, and the second when paths through vertex 2 do. Each round widens the set of allowed intermediate vertices by one.
Common errors
| Mistake | Effect |
|---|---|
| Putting `k` inside the `i` or `j` loop | Some pairs are finalized before the intermediate paths they need exist, which gives wrong distances |
| Leaving `dist[i][i]` as `inf` | Paths through `k` cannot be formed correctly, and later negative-cycle checks break |
| Overwriting parallel edges with the last one read | A heavier edge can replace a lighter one |
| Using a large integer such as `10**9` as "infinity" | Adding negative weights to it creates fake finite distances |
Exercise
In the example, add the edge (3, 0, 2). What is dist[3][2] after the algorithm finishes, and through which intermediate vertices does the path go?
Show answer
dist[3][2] is 3. The path is 3 -> 0 -> 1 -> 2, with weight 2 + 4 + (-3) = 3, so it passes through vertices 0 and 1. The direct route through 0 alone, 3 -> 0 -> 2, costs 7.
Exercise
Why does skipping the inner j loop when dist[i][k] is inf never change the result?
Show answer
When dist[i][k] is inf, dist[i][k] + dist[k][j] is inf for every j. An inf value can never be strictly less than dist[i][j], so no update would happen anyway.