One table for all pairs
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.
The table d starts with what we know already. d[i][j] is the cost of the direct edge from i to j, 0 on the diagonal, and ∞ (Python's float("inf")) where there is no edge yet.
One rule does all the work. For a middle vertex k, if going i → k → j costs less than d[i][j], write the cheaper cost in. Try it for every pair i, j, first with k = 0, then 1, 2 and 3.
Four rounds of k
Round k = 0: may a route pass through 0? Only 3 has an edge into 0. 3 → 0 → 1 costs 2 + 3 = 5, beating ∞, and 3 → 0 → 2 costs 2 + 8 = 10. Two cells improve.
Round k = 1. 0 → 1 → 2 costs 3 + 2 = 5, beating 8. 0 → 1 → 3 costs 3 + 7 = 10. 3 → 1 → 2 costs 5 + 2 = 7, reusing round 0's 5.
Round k = 2. 0 → 2 → 3 costs 5 + 1 = 6, beating 10. 1 → 2 → 3 costs 2 + 1 = 3, beating 7. Each sum reads row 2 and column 2: the lit cross.
Round k = 3, the last. 1 → 3 → 0 costs 3 + 2 = 5, 2 → 3 → 0 costs 1 + 2 = 3, and 2 → 3 → 1 costs 1 + 5 = 6. No ∞ is left.
Reading and trusting it
Done: each cell is now a shortest distance. d[2][1] = 6 is the route 2 → 3 → 0 → 1, costing 1 + 2 + 3. The table keeps costs only; to rebuild routes, keep a second table of next stops.
Why does it work? After round k, d[i][j] is the cheapest route whose middle stops all come from 0 to k. A best route through k is a best i → k part plus a best k → j part, both already in the table.
Three nested loops of n, so n³ checks: 4³ = 64 here. That is Θ(n³) time and one n × n table, Θ(n²) memory. Negative edges are fine; a negative cycle shows up as a negative number on the diagonal.
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.