313. Floyd-Warshall

All-pairs shortest path algorithm — finds the shortest distance from every node to every other node in 𝑂(𝑉3).

Useful when you need the distance matrix for many queries, vs running Dijkstra from each source (𝑂(𝑉(𝑉+𝐸)log𝑉)).

313.1. Algorithm

Dynamic programming. Let 𝑑𝑘(𝑖,𝑗) = shortest path from 𝑖 to 𝑗 using only intermediate nodes from {1,,𝑘}:

𝑑𝑘(𝑖,𝑗)=min(𝑑𝑘1(𝑖,𝑗),𝑑𝑘1(𝑖,𝑘)+𝑑𝑘1(𝑘,𝑗))

Either use node 𝑘 as a stop (split at 𝑘) or don’t (same path).

Initialize D[i][j] = edge weight (or ∞ if no edge), D[i][i] = 0
For k = 1, 2, …, V:
    For i = 1, …, V:
        For j = 1, …, V:
            D[i][j] ← min(D[i][j], D[i][k] + D[k][j])
Return D

Three nested loops → 𝑂(𝑉3). Space 𝑂(𝑉2) (the matrix). Update in place — no need for separate “old” and “new” matrices.

313.2. Edge cases

313.3. Compared to single-source alternatives

Floyd-Warshall𝑉 × Dijkstra𝑉 × Bellman-Ford
All-pairs cost𝑂(𝑉3)𝑂(𝑉(𝑉+𝐸)log𝑉)𝑂(𝑉2𝐸)
Negative edges?yesnoyes
Memory𝑂(𝑉2)𝑂(𝑉2)𝑂(𝑉2)
Dense graphs (𝐸𝑉2)𝑂(𝑉3) — best𝑂(𝑉3log𝑉)𝑂(𝑉4)
Sparse graphs (𝐸𝑉)𝑂(𝑉3)𝑂(𝑉2log𝑉) — best𝑂(𝑉3)

Floyd-Warshall is best for dense graphs with potentially negative edges.

313.4. Path reconstruction

To recover paths (not just distances), maintain a predecessor matrix 𝜋[𝑖][𝑗] alongside 𝐷:

When updating D[i][j] via D[i][k] + D[k][j]:
    π[i][j] ← π[k][j]

Then trace back from 𝑗 to 𝑖 via 𝜋.

313.5. Applications

313.6. See also