0381222713j=0j=1j=2j=3i=0i=1i=2i=31INF = float("inf")2def floyd_warshall(d):3 n = len(d)4 for k in range(n):5 for i in range(n):6 for j in range(n):7 if d[i][k] + d[k][j] < d[i][j]:8 d[i][j] = d[i][k] + d[k][j]9 return dkchecksimproved
Tiles: the table d, best known cost from row i to column jThe cross: row k and column k, the only cells the sums readChips: d[i][k] and d[k][j] flying in when their sum is cheaperA weighted directed graph and its 4 × 4 distance table d, which starts with the direct edge costs. In round k the glowing cross marks row k and column k; the probe checks all 16 cells in loop order, and where i → k → j is cheaper the chips d[i][k] and d[k][j] fly into cell (i, j) while a walker runs that route on the graph. Four rounds, 64 checks, 10 improvements: the table ends holding every shortest distance.

One table for all pairs

  1. A directed graph with weights: 4 vertices and 6 one-way edges, each with a cost. We want the cheapest route from every vertex to every other: 4 × 4 = 16 answers. Floyd-Warshall finds them all with one table.

Four rounds of k

Reading and trusting it

What happens

;; step 1/10 · problem
vertices 0..3, edges (from → to: cost):
  0 → 1: 3
  0 → 2: 8
  1 → 2: 2
  1 → 3: 7
  2 → 3: 1
  3 → 0: 2

a route's cost is the sum of its edge costs
goal: the cheapest cost for all 16 ordered pairs (i, j)

Floyd-Warshall is dynamic programming (MIT 6.006, Lecture 17): the subproblem is the cheapest route from i to j using only middle stops from {0..k}, and round k needs only round k - 1. Updating one table in place is safe because round k never changes row k or column k (d[k][k] = 0). Negative edge costs are allowed. If the graph has a negative cycle, shortest paths are not defined; Floyd-Warshall then leaves some d[i][i] below 0, which is how Sedgewick and Wayne's FloydWarshall.java detects it.