Floyd-Warshall solves the all-pairs shortest paths (APSP) problem using dynamic programming. It is particularly suited to dense graphs, running in Θ(∣V∣3) time and Θ(∣V∣2) space (in-place optimisation). It handles negative edge weights but, like all shortest-path algorithms, requires that no negative-weight cycles exist.
The DP Recurrence
Number the vertices 1,2,…,n. Let dij(k) be the weight of a shortest path from i to j using only intermediate vertices from the set {1,2,…,k}. The base case k=0 uses no intermediate vertices:
dij(0)=⎩⎨⎧0w(i,j)∞if i=jif (i,j)∈Eotherwise
For k≥1, vertex k is either used as an intermediate vertex or not:
dij(k)=min(dij(k−1),dik(k−1)+dkj(k−1))
After k=n, we have the full all-pairs shortest distances.
Pseudocode
FLOYD-WARSHALL(W): n = number of vertices D^(0) = W // W is the weight matrix (∞ for absent edges) for k = 1 to n: let D^(k) be a new n × n matrix for i = 1 to n: for j = 1 to n: D^(k)[i][j] = min(D^(k-1)[i][j], D^(k-1)[i][k] + D^(k-1)[k][j]) return D^(n)
Space optimisation: The D(k−1) matrix can be overwritten to produce D(k) in place because dik(k−1)=dik(k) and dkj(k−1)=dkj(k) (paths where k is an intermediate vertex cannot have k as an endpoint). So a single n×n matrix suffices.
Worked Example
Consider a graph with V={1,2,3,4}, edges and weights:
The final matrix gives all-pairs distances. For example, δ(4,3)=7 via path 4→1→2→3 (cost 2+3+2=7).
Predecessor Matrix
To reconstruct paths, maintain a predecessor matrix Π(k) in parallel. Initialise πij(0)=i if (i,j)∈E or i=j, else NIL. Update alongside the distance matrix: if the dik+dkj path is chosen, set πij(k)=πkj(k−1).
Transitive Closure
Floyd-Warshall can compute the transitive closureG∗ of a graph: an edge (i,j) exists in G∗ iff there is a path from i to j in G. Replace MIN with logical OR and + with logical AND. Initialise dij(0)=1 if i=j or (i,j)∈E, 0 otherwise. Running the same triple loop yields the reachability matrix in Θ(∣V∣3).
For DAGs, the transitive closure can be computed more efficiently by processing vertices in topological order.
Comparison with Johnson
Algorithm
Time
Space
Best for
Floyd-Warshall
Θ(V3)
Θ(V2)
Dense graphs
Johnson
O(V2logV+VE)
Θ(V2)
Sparse graphs
When ∣E∣=Θ(∣V∣2), both are Θ(∣V∣3), but Floyd-Warshall has lower constant factors and is simpler to implement.
Summary
Property
Detail
Type
Dynamic programming
Recurrence
dij(k)=min(dij(k−1),dik(k−1)+dkj(k−1))
Base case
dij(0)=w(i,j) or 0 for i=j
Time
Θ(V3)
Space
Θ(V2) (in-place)
Negative weights
Handled (no negative cycles)
Transitive closure
Replace min/+ with OR/AND
Past paper questions: y2026p1q10(c,d) (DAG transitive closure optimisation).