Introduction

The all-pairs shortest-paths problem asks for δ(i,j)\delta(i,j) for every pair of vertices. Running a single-source algorithm from each vertex works when weights are nonnegative (Dijkstra nn times) or in general (Bellman-Ford nn times), but the classical GATE algorithm is Floyd-Warshall: a Θ(n3)\Theta(n^3) DP that allows negative weights and detects negative cycles by inspecting the diagonal.

Prerequisites

Core concepts

DP state

Number vertices 1..n1..n. Let dij(k)d_{ij}^{(k)} be the shortest-path weight from ii to jj using only intermediate vertices in {1,…,k}\{1,\ldots,k\}.

dij(0)=wij,dij(k)=min⁡(dij(k−1), dik(k−1)+dkj(k−1)).d_{ij}^{(0)} = w_{ij}, \qquad d_{ij}^{(k)} = \min\bigl(d_{ij}^{(k-1)},\, d_{ik}^{(k-1)} + d_{kj}^{(k-1)}\bigr).

The answer is dij(n)d_{ij}^{(n)}. Space Θ(n2)\Theta(n^2) suffices by overwriting a single matrix in place.

Negative cycles

Some final diagonal entry is negative if and only if the graph contains a negative cycle. Here a cycle is simple (no repeated vertices apart from its endpoints), while a closed walk may repeat vertices. A negative diagonal entry at ii certifies a negative closed walk through ii, not necessarily a negative simple cycle containing ii. A zero diagonal does not certify an unaffected source: the walk distance from uu to vv is unbounded below whenever uu can reach a negative cycle that can reach vv. The finite matrix entries are not shortest-walk distances for those affected pairs.

Transitive closure

Replacing min⁡\min and ++ by ∨\lor and ∧\land on a boolean adjacency matrix yields the reachability (transitive closure) matrix in the same Θ(n3)\Theta(n^3) loops: tij(k)=tij(k−1)∨(tik(k−1)∧tkj(k−1))t_{ij}^{(k)} = t_{ij}^{(k-1)} \lor \bigl(t_{ik}^{(k-1)} \land t_{kj}^{(k-1)}\bigr), with tij(0)=1t_{ij}^{(0)} = 1 when i=ji = j or (i,j)∈E(i,j) \in E. CLRS presents this in Section 25.2. For the four-vertex example below every vertex reaches every other, so the closure is all ones. Delete the edge 2→12\to 1, the only edge into vertex 1, and column 1 of the closure becomes 1,0,0,01, 0, 0, 0: only vertex 1 itself reaches 1.

Algorithms and pseudocode

Pseudocode uses 1-based matrices and <- for assignment.

Text
FLOYD-WARSHALL(W)
1  n <- W.rows
2  D^(0) <- W
3  for k <- 1 to n
4      let D^(k) be a new n x n matrix
5      for i <- 1 to n
6          for j <- 1 to n
7              D^(k)[i,j] <- min(D^(k-1)[i,j], D^(k-1)[i,k] + D^(k-1)[k,j])
8  return D^(n)

In-place variant. Drop the superscripts and update D[i,j] in the triple loop; the algorithm remains correct (CLRS Exercise 25.2-4).

The loop over kk must be outermost. The recurrence needs every entry of level k−1k-1 before level kk starts. Writing the loops as for i, for j, for k (with kk innermost) computes each D[i,j]D[i,j] once, from entries that may not be final yet. Counterexample: the path 1→2→4→31\to 2\to 4\to 3 with every weight 1. With kk innermost, D[1,3]D[1,3] is computed while D[1,4]D[1,4] is still ∞\infty (column 3 comes before column 4), and no later step revisits D[1,3]D[1,3]. It ends at ∞\infty instead of 3. With kk outermost the answer is 3.

Time / space. Θ(n3)\Theta(n^3) time, Θ(n2)\Theta(n^2) space. Independent of the number of edges, so dense graphs are the natural fit. For sparse nonnegative graphs, nn Dijkstra runs in O(VElg⁡V)O(VE\lg V) can be faster.

Reconstruction. Keep a predecessor matrix πij\pi_{ij}: initially πij=i\pi_{ij} = i if (i,j)∈E(i,j) \in E and NIL otherwise; when the path through kk improves i→ji\to j, set πij←πkj\pi_{ij} \leftarrow \pi_{kj}. Recursively print the path from ii to πij\pi_{ij} then the edge to jj. In the example below, π1,3=4\pi_{1,3} = 4 and π1,4=1\pi_{1,4} = 1, so the path is 1→4→31\to 4\to 3 of weight 5+2=75 + 2 = 7.

Edge cases. Missing edges start as ∞\infty; ∞+x=∞\infty + x = \infty. Initialize off-diagonal W[i,j]W[i,j] to the minimum weight among direct edges from ii to jj, or ∞\infty if none exists. Initialize W[i,i]=min⁡(0,minimum self-loop weight at i)W[i,i]=\min(0,\text{minimum self-loop weight at }i), interpreting a missing self-loop as ∞\infty. A negative self-loop must be retained; it is already a negative cycle.

Mathematical explanation

Optimal substructure

A shortest i→ji\to j path that uses intermediate vertices from {1,…,k}\{1,\ldots,k\} either avoids kk entirely (then it equals the (k−1)(k-1) answer) or splits as a shortest i→ki\to k path and a shortest k→jk\to j path, both using intermediates from {1,…,k−1}\{1,\ldots,k-1\}. Those are the only two options, justifying the recurrence.

Comparison with repeated single-source

MethodWeightsTime (adj. lists / matrix)
n×n\times Dijkstra (binary heap)nonnegativeO(VElg⁡V)O(VE\lg V)
n×n\times Bellman-FordarbitraryO(V2E)O(V^2 E)
Floyd-WarshallarbitraryΘ(V3)\Theta(V^3)
Johnson (related material)arbitrary, no neg. cycleO(VE+V2lg⁡V)O(VE + V^2\lg V) with Fib. heaps

Johnson's algorithm reweights by a Bellman-Ford potential then runs Dijkstra from every vertex; it is the sparse-graph alternative when negatives appear but no negative cycle exists.

Worked examples

Four-vertex run

Weight matrix WW (00 on the diagonal, ∞\infty written as inf):

W=(03∞520∞4∞10∞∞∞20).W = \begin{pmatrix} 0 & 3 & \infty & 5 \\ 2 & 0 & \infty & 4 \\ \infty & 1 & 0 & \infty \\ \infty & \infty & 2 & 0 \end{pmatrix}.

After k=1k=1 (through vertex 1): d2,4d_{2,4} stays 4; d2,1+d1,4=2+5=7d_{2,1}+d_{1,4}=2+5=7 does not improve. After k=2k=2: d3,1d_{3,1} becomes 1+2=31+2=3, d3,4d_{3,4} becomes 1+4=51+4=5. After k=3k=3: d4,1d_{4,1} becomes 2+3=52+3=5, d4,2d_{4,2} becomes 2+1=32+1=3. After k=4k=4: d1,3d_{1,3} becomes 5+2=75+2=7, d2,3d_{2,3} becomes 4+2=64+2=6. Final matrix:

D(4)=(0375206431055320).D^{(4)} = \begin{pmatrix} 0 & 3 & 7 & 5 \\ 2 & 0 & 6 & 4 \\ 3 & 1 & 0 & 5 \\ 5 & 3 & 2 & 0 \end{pmatrix}.

All diagonal entries are 0, so no negative cycle.

Floyd-Warshall matrices after each k
Figure 1. Floyd-Warshall on the four-vertex example: the matrices D(0)=WD^{(0)}=W through D(4)D^{(4)} with final distances as in the worked table; the diagonal stays zero (no negative cycle).

Negative cycle on the diagonal

Change w4,1w_{4,1} from ∞\infty to −10-10. The cycle 1→4→11\to 4\to 1 has weight 5−10=−55 - 10 = -5. After round k=4k = 4, d1,1d_{1,1}, d4,4d_{4,4} and d2,2d_{2,2} are negative (vertex 2 lies on the cycle 2→4→1→22\to 4\to 1\to 2 of weight 4−10+3=−34 - 10 + 3 = -3). d3,3d_{3,3} stays 0: every cycle through vertex 3 has positive weight, even though 3 can reach a negative cycle. A zero diagonal entry does not rule out reaching a negative cycle; it does not rule out a negative closed walk through the vertex, obtained by repeating a reachable negative cycle sufficiently often and returning.

In-place update subtlety

When the triple loop updates D[i,j]D[i,j] in place, the right-hand side reads D[i,k]D[i,k] and D[k,j]D[k,j]. These two entries do not change during round kk: dik(k)=min⁡(dik(k−1),dik(k−1)+dkk(k−1))d_{ik}^{(k)} = \min(d_{ik}^{(k-1)}, d_{ik}^{(k-1)} + d_{kk}^{(k-1)}), and dkk=0d_{kk} = 0 when there is no negative cycle, so row kk and column kk are the same at levels k−1k-1 and kk. Overwriting one matrix is therefore exactly as good as keeping two. The same in-place trick is not safe for every DP; matrix-chain multiplication, for example, needs the strict length order.

Space and early termination

Floyd-Warshall offers no useful early termination: even if a round leaves the matrix unchanged, later kk values can still improve entries. Space is Θ(n2)\Theta(n^2) for distances plus Θ(n2)\Theta(n^2) if a full predecessor matrix is stored. For a single pair query on a sparse nonnegative graph, a bidirectional Dijkstra is preferable; Floyd-Warshall earns its keep when many pairs are needed or when negatives appear without a cycle.

Important properties and observations

  • Floyd-Warshall always runs in Θ(n3)\Theta(n^3) whether the graph is sparse or dense: the update line runs exactly n3n^3 times (64 for n=4n = 4).
  • Matrix-multiplication view is different (CLRS Section 25.1): L(m)L^{(m)} allows paths of at most mm edges and is built with a min-plus "product". Repeated squaring needs ⌈lg⁡(n−1)⌉\lceil \lg(n-1) \rceil products, Θ(n3lg⁡n)\Theta(n^3 \lg n) in total. Floyd-Warshall instead indexes by the set of allowed intermediate vertices and reaches Θ(n3)\Theta(n^3).
  • Johnson's algorithm (related material, CLRS Section 25.3): add a new vertex with 0-weight edges to all vertices, run Bellman-Ford from it to get hh, reweight by w(u,v)+h(u)−h(v)≥0w(u,v) + h(u) - h(v) \ge 0, then run Dijkstra from every vertex and undo the reweighting.
  • The algorithm does not early-exit; even if the graph is a DAG the loops still execute fully (the DAG single-source method is better for one source).
  • Order of i,ji,j inside the kk loop does not matter for the in-place version's correctness on distances.
  • Common misconceptions.
    • "Floyd-Warshall requires nonnegative weights." False; it is designed for negatives (and reports cycles).
    • "A zero on the diagonal always means no cycle." A zero is normal (empty path); a negative diagonal entry means a negative cycle.
    • "The algorithm lists the paths." Distances yes; paths need the predecessor matrix.

GATE examination perspective

  • FILL ONE ENTRY. Compute dij(k)d_{ij}^{(k)} from the recurrence with a partially filled matrix. First identify the largest kk already applied, so the recurrence is used at the right level.
  • LOOP ORDER. kk must be the outermost loop; a code fragment with kk innermost is wrong (path 1→2→4→31\to 2\to 4\to 3 example).
  • NEGATIVE CYCLE. Read the diagonal after k=nk=n: a negative diid_{ii} certifies a negative closed walk through ii. Some diagonal is negative iff a negative cycle exists; it need not be a simple cycle through every such ii.
  • TRANSITIVE CLOSURE. Same loops with OR and AND; tii=1t_{ii} = 1 by convention.
  • COMPLEXITY. Θ(n3)\Theta(n^3), independent of EE; exactly n3n^3 executions of the update line.
  • CHOOSE VERSUS DIJKSTRA. Dense or negative weights: Floyd-Warshall; sparse and nonnegative: repeated Dijkstra; sparse with negatives but no negative cycle: Johnson.
  • PATHS. Distances alone do not give the path; use πij\pi_{ij} and update it exactly when the distance improves.

Summary

Sources

  1. T. H. Cormen, C. E. Leiserson, R. L. Rivest, C. Stein, Introduction to Algorithms, 3rd ed., MIT Press, 2009, Chapter 25, Sections 25.1 (shortest paths and matrix multiplication), 25.2 (Floyd-Warshall, including transitive closure) and 25.3 (Johnson's algorithm); Exercises 25.2-4 (in-place update) and 25.2-6 (negative-cycle detection).

Next steps