Every pair at once: Floyd–Warshall
🌍 In real life. A bus company prints a table on the back of every ticket: the shortest travel time between every pair of its towns. Dijkstra (Lesson 54.2) answers "from one town to all others"; to fill the whole table you could run it once from every town. Floyd–Warshall fills the whole table directly, with three nested loops and no heap, and it even copes with negative edges (a road with a toll refund, say), as long as no loop has a negative total.
The idea in one sentence: dist[i][j] starts as the direct road, and for each town k in turn, every pair (i, j) checks whether going through k is shorter, dist[i][k] + dist[k][j]; after all k, every entry is the shortest route.
Its words:
- all-pairs shortest paths: the distance from every vertex to every other
- intermediate vertex: a stop in the middle of a route, not its start or end
- relax through k: replace
dist[i][j]bydist[i][k] + dist[k][j]when that is smaller - negative cycle: a loop whose lengths add up to less than 0; then "shortest" has no meaning
Step by step, for roads 0 → 1 (4), 1 → 2 (1), 0 → 2 (7):
- To start, only direct roads: from 0,
[0, 4, 7]. - k = 0: no road leads into town 0, so going through it helps nobody.
- k = 1: 0 → 1 → 2 costs 4 + 1 = 5, less than 7:
dist[0][2] = 5. - k = 2: nothing improves. The row for town 0 is
[0, 4, 5].
Why it is correct. Claim: after the round for k, dist[i][j] is the shortest route from i to j that uses only towns 0..k as middle stops. Before any round, only direct roads count: true. In round k, the best route through 0..k either avoids k (already in the table) or passes through k once, made of a best route i → k and a best route k → j using only 0..k−1 (both already in the table). Taking the smaller of the two keeps the claim true. After the last round every town is allowed: the table holds the true shortest distances. That is why k must be the outermost loop.
Negative edges and cycles. Nothing in the argument needs lengths to be positive, so negative edges are fine. A negative cycle shows up on the diagonal: if some dist[i][i] ends below 0, a loop through i gets shorter every time round, and no shortest route exists.
What it costs, by counting. n rounds of n × n checks: O(n³) time and O(n²) memory. For n = 400 that is 64 million steps, slow in Python but simple. With non-negative lengths and few roads, Dijkstra from every town costs about O(n × E log n), which is faster for sparse graphs; Floyd–Warshall wins on dense, small graphs and on negative edges.
INF = float("inf")
def floyd(n, roads): # roads: (from, to, length), one way
dist = [[0 if i == j else INF for j in range(n)] for i in range(n)]
for a, b, w in roads:
dist[a][b] = min(dist[a][b], w) # keep the shortest of parallel roads
for k in range(n): # k: the stop now allowed in the middle
for i in range(n):
for j in range(n):
if dist[i][k] + dist[k][j] < dist[i][j]:
dist[i][j] = dist[i][k] + dist[k][j]
return dist
roads = [(0, 1, 4), (1, 2, 1), (0, 2, 7), (2, 3, 2), (3, 0, 3)]
for row in floyd(4, roads):
print(row)
loop = floyd(3, [(0, 1, 1), (1, 2, -3), (2, 0, 1)])
print("negative cycle:", any(loop[i][i] < 0 for i in range(3)))Mistakes and edge cases.
- k not outermost. With k innermost,
dist[i][j]is finished before the routes it depends on are known: for roads 0 → 1, 1 → 3, 3 → 2 the distance from 0 to 2 staysinf. - Forgetting the diagonal.
dist[i][i]must start at 0; withinfthere, routes through i are never found from i itself. - Overwriting parallel roads. Two roads between the same towns: keep the shorter with
min, not the last one read. - Undirected roads. Store both directions:
dist[a][b]anddist[b][a]. - Large n. n = 2,000 is 8 billion steps: far too slow. Use Dijkstra from the towns you actually need.
Quiz
What does this print?
INF = float("inf") def floyd(n, roads): # roads: (from, to, length), one way dist = [[0 if i == j else INF for j in range(n)] for i in range(n)] for a, b, w in roads: dist[a][b] = min(dist[a][b], w) # keep the shortest of parallel roads for k in range(n): # k: the stop now allowed in the middle for i in range(n): for j in range(n): if dist[i][k] + dist[k][j] < dist[i][j]: dist[i][j] = dist[i][k] + dist[k][j] return dist d = floyd(3, [(0, 1, 2), (1, 2, 2), (2, 0, 1)]) print(d[0][2], d[2][1], d[1][0])Why must the loop over k be the outermost one?
- Round k uses the best routes through 0..k−1, which must all be finished first
- To make the code shorter
- It only matters for negative edges
After Floyd–Warshall, dist[3][3] is −2. What does that mean?
- Town 3 is on a negative cycle, so shortest routes through it don't exist
- It takes −2 to stay in town 3
- The table is correct
For roads [(0, 1, 1), (1, 3, 1), (3, 2, 1)] the distance from 0 to 2 should be 3, but this gives inf. Which line is wrong?
def floyd(n, roads): dist = [[0 if i == j else INF for j in range(n)] for i in range(n)] for a, b, w in roads: dist[a][b] = min(dist[a][b], w) for i in range(n): for j in range(n): for k in range(n): if dist[i][k] + dist[k][j] < dist[i][j]: dist[i][j] = dist[i][k] + dist[k][j] return dist
Coding tasks
Write
floyd(n, roads): towns 0..n−1,roadsare one-way(from, to, length). Return the n × n table of shortest distances, withfloat("inf")where there is no route. There are no negative cycles.Write
has_negative_cycle(n, roads): True if some loop of one-way roads adds up to less than 0.