All-Pairs Shortest Paths: Floyd-Warshall and Johnson's Algorithm
Anchor (Master): Cormen, Leiserson, Rivest & Stein 2022 Introduction to Algorithms 4e (MIT Press) §25.1-25.3; Tarjan 1983 Data Structures and Network Algorithms (SIAM) Ch. 7 (all-pairs shortest paths, relationship to matrix multiplication over semirings, Floyd-Warshall as min-plus matrix multiplication)
Intuition Beginner
You have a road map with cities as vertices and roads as edges, each with a travel time. You want to know the fastest route between every pair of cities, not just two specific ones. This is the all-pairs shortest-paths problem.
One approach: run Dijkstra's algorithm from every city. This works but can be slow if the map is dense. A different approach, Floyd-Warshall, asks a clever question: what is the shortest path from city A to city B if you are only allowed to pass through the first cities as intermediate stops?
As grows from 0 to , the answer gets better and better. When , you can only use direct roads. When , you can also stop at city 1. When , you can stop anywhere, and you have the true shortest paths.
Each step is simple: the shortest path from A to B using cities either does not use city (so it equals the previous answer) or does use city (so it is the shortest A-to- plus shortest -to-B). Take the minimum of these two options.
Johnson's algorithm takes a different approach. It handles negative edge weights by "reweighting" the graph so that all weights become non-negative, then runs Dijkstra from every vertex. The reweighting preserves shortest paths, so the answers are correct.
Visual Beginner
A weighted graph with 4 vertices:
2 5
(0)───→(1)───→(2)
│ ↑ │
│ -1 │ 1 │
↓ │ ↓
(3)─────┘ (4)
3Wait, let me simplify. A 4-vertex graph:
3 1
0 ──→ 1 ──→ 2
│ ↑
│ 8 │ 2
↓ │
3 ──────────┘
5Floyd-Warshall fills in a distance matrix step by step.
| Step | 0→0 | 0→1 | 0→2 | 0→3 | 1→2 |
|---|---|---|---|---|---|
| k=0 | 0 | 3 | inf | 8 | 1 |
| k=1 | 0 | 3 | 4 | 8 | 1 |
| k=2 | 0 | 3 | 4 | 8 | 1 |
| k=3 | 0 | 3 | 4 | 8 | 1 |
At : shortest 0→2 using intermediate {1} = min(4, 3+1) = 4. At : shortest 0→3 using {0,1,2,3} = min(8, 4+5+2...) already 8.
Worked example Beginner
We run Floyd-Warshall on a 4-vertex graph with edge weights:
- 0→1: 3, 0→3: 8, 1→2: 1, 2→3: 2, 3→1: -4.
Initial distance matrix (, only direct edges):
0 1 2 3
0 [ 0 3 ∞ 8 ]
1 [ ∞ 0 1 ∞ ]
2 [ ∞ ∞ 0 2 ]
3 [ ∞ -4 ∞ 0 ]Step (can use vertex 1 as intermediate):
- 0→2: min(∞, 3+1) = 4. 0→3: min(8, 3+∞) = 8. 3→2: min(∞, -4+1) = -3.
0 1 2 3
0 [ 0 3 4 8 ]
1 [ ∞ 0 1 ∞ ]
2 [ ∞ ∞ 0 2 ]
3 [ ∞ -4 -3 0 ]Step (can use vertices 1, 2):
- 0→3: min(8, 4+2) = 6. 1→3: min(∞, 1+2) = 3. 3→3: min(0, -3+2) = -1.
Wait — a negative diagonal entry means a negative cycle. Let me recalculate. 3→2→3 = -3+2 = -1. And 3→3 = 0. So min(0, -1) = -1. This indicates a negative-weight cycle through vertex 3.
Actually, let me redo with a graph that has no negative cycles. Remove the edge 3→1. Then:
Initial ():
0 1 2 3
0 [ 0 3 ∞ 8 ]
1 [ ∞ 0 1 ∞ ]
2 [ ∞ ∞ 0 2 ]
3 [ ∞ ∞ ∞ 0 ]: 0→2: min(∞, 3+1) = 4. : 0→3: min(8, 4+2) = 6. 1→3: min(∞, 1+2) = 3. : no improvements (3 has no outgoing edges except to itself).
Final matrix:
0 1 2 3
0 [ 0 3 4 6 ]
1 [ ∞ 0 1 3 ]
2 [ ∞ ∞ 0 2 ]
3 [ ∞ ∞ ∞ 0 ]Shortest path 0→3: 0→1→2→3 with weight 3+1+2 = 6.
Check your understanding Beginner
Formal definition Intermediate+
Definition (all-pairs shortest-paths). Given a weighted directed graph with and , the all-pairs shortest-paths problem is to compute an matrix where , the weight of a shortest path from to , and a predecessor matrix for path reconstruction.
Definition (Floyd-Warshall recurrence). Define as the weight of a shortest path from to using only intermediate vertices from . The recurrence is:
The final answer is .
Theorem (Floyd-Warshall correctness). If has no negative-weight cycles, then for all .
Definition (Johnson's reweighting). Given , add a new vertex with zero-weight edges to all vertices. Run Bellman-Ford from to compute shortest-path distances . Define the reweighted graph .
Lemma (reweighting preserves shortest paths). If is any path from to , then . Therefore, is a shortest path under if and only if is a shortest path under .
Furthermore, if has no negative-weight cycles, then for all edges, enabling the use of Dijkstra's algorithm.
Counterexamples to common slips
"Running Dijkstra from every vertex solves APSP in ." This is correct only for non-negative edge weights. If the graph has negative edges (but no negative cycles), Dijkstra is incorrect and Johnson's reweighting is needed first.
"Floyd-Warshall is always slower than running Dijkstra times." For dense graphs (), Floyd-Warshall's matches runs of Dijkstra at each. For sparse graphs, Dijkstra runs take which is faster.
"Johnson's algorithm requires no negative edges." Johnson's handles negative edges by reweighting them away. It requires no negative cycles, not no negative edges.
Key theorem with proof Intermediate+
Theorem (Floyd-Warshall correctness). For all and , equals the weight of a shortest path from to with all intermediate vertices in .
Proof. By induction on .
Base: . No intermediate vertices are allowed, so the only paths are direct edges or the empty path (when ). is set to exactly these values.
Inductive step: assume is correct. Consider a shortest path from to using intermediates in . Either does not use vertex as an intermediate, in which case , or uses . In the latter case, decomposes as where the subpath uses intermediates in (it cannot pass through before reaching ) and similarly for . So . Taking the minimum of these two options gives .
Bridge. The Floyd-Warshall recurrence is the foundational reason all-pairs shortest paths can be computed in time: it builds up the solution by progressively allowing more intermediate vertices, and each step is a simple minimisation. This builds toward the transitive closure computation, where the same structure appears with OR replacing MIN and AND replacing PLUS, and it appears again in min-plus matrix multiplication, where the Floyd-Warshall algorithm is exactly the computation of the closure of the weight matrix over the min-plus semiring. The central insight is that shortest paths compose: the shortest -to- path through is the concatenation of the shortest -to- and -to- paths. Putting these together with Johnson's reweighting yields a complete toolkit for APSP: Floyd-Warshall for dense or small graphs, Johnson for sparse graphs with negative edges.
Exercises Intermediate+
Lean formalization Intermediate+
Mathlib has Graph.Weighted and basic graph definitions but no formalisation of Floyd-Warshall or Johnson's algorithm. The foundational gap is the absence of an APSP matrix computation with correctness proofs. The Floyd-Warshall recurrence and its inductive proof require a formalisation of "paths using intermediates in ." Johnson's reweighting requires the shortest-path potential and the proof that . This unit ships without a lean_module.
Advanced results Master
Three results extend the basic APSP theory.
Theorem 1 (min-plus semiring). The Floyd-Warshall algorithm is a computation in the min-plus semiring . The distance matrix is the closure of the weight matrix in this semiring: where .
This algebraic perspective unifies shortest paths with other semiring computations. Replacing with gives transitive closure. Replacing with gives matrix powers. The Floyd-Warshall algorithm is a specialisation of Kleene's algorithm for computing semiring closures [Tarjan Ch. 7].
Theorem 2 (APSP via matrix multiplication). If matrix multiplication over a ring can be done in time , then APSP can be solved in time where satisfies , using the relationship between min-plus products and standard matrix multiplication over appropriate rings.
The current best APSP algorithm for dense graphs is by Williams (2018), running in time, using fast matrix multiplication techniques applied to the min-plus product.
Theorem 3 (negative cycle detection). Floyd-Warshall detects a negative-weight cycle if and only if some diagonal entry . The detection takes no additional time beyond the main algorithm.
Synthesis. The Floyd-Warshall and Johnson algorithms are the foundational reason APSP can be solved efficiently: Floyd-Warshall provides a simple solution for all graphs, while Johnson adapts Dijkstra to handle negative weights via reweighting. The central insight is that shortest paths compose — the path has weight equal to the sum of its parts — and this is exactly the property exploited by both algorithms. This builds toward the semiring generalisation, where the same algorithmic structure computes transitive closure, matrix powers, and other algebraic closures. Putting these together with the single-source shortest-path algorithms (Bellman-Ford, Dijkstra) yields a complete shortest-path toolkit: choose the algorithm based on graph density and edge weight properties.
Full proof set Master
Proposition 1 (Floyd-Warshall correctness). For all and all , equals the weight of a shortest path from to using only vertices in as intermediaries.
Proof. By strong induction on .
Base (): No intermediate vertices. The only paths are direct edges (weight ) or the identity path to (weight 0). is defined to match these values exactly.
Inductive step: Assume the claim for . Let be a shortest path from to using intermediates in .
Case 1: does not contain vertex . Then uses only intermediates in , so .
Case 2: contains vertex . Decompose as where both subpaths use only intermediates in (if appeared in a subpath, it would create a cycle that could be removed without increasing weight, contradicting minimality). Then .
In either case, . And is achievable by one of the two cases, so .
Proposition 2 (Johnson's reweighting preserves shortest paths). Let be any function satisfying for all . Define . Then is a shortest -to- path under iff is a shortest -to- path under .
Proof. For any path from to :
The offset depends only on the endpoints, not on the path. So if minimises among all -to- paths, it also minimises , and vice versa.
Proposition 3 (reweighting yields non-negative weights). If has no negative-weight cycles and for an added source , then for all .
Proof. By the triangle inequality for shortest paths, for every edge . Rearranging: , i.e., .
Connections Master
47.04.01— Amortized analysis applies to sequences of shortest-path queries; the Floyd-Warshall algorithm precomputes all answers in one pass.47.04.06— MST algorithms find minimum-weight spanning subgraphs; APSP algorithms find minimum-weight paths. Both are fundamental graph optimisation primitives.47.04.03— Min-cost flow algorithms use shortest-path computations as a subroutine; Johnson's reweighting is used to handle negative reduced costs.50.03.01— Big-O analysis bounds the running times of both Floyd-Warshall () and Johnson's ().
Historical & philosophical context Master
The Floyd-Warshall algorithm was published by Robert Floyd in 1962, though the same idea was discovered independently by Bernard Roy in 1959 and Stephen Warshall in 1962 (for transitive closure). The algorithm is an instance of a more general technique: computing the closure of a matrix over a closed semiring, as formalised by Lehmann (1977) and later by Tarjan [CLRS §25.2 notes].
Johnson's algorithm was published by Donald Johnson in 1977. The key insight — that shortest-path potentials can be used to reweight edges non-negatively — is a discrete analogue of the concept of gauge transformations in physics, where a transformation preserves the physical content while simplifying the equations. The potential function plays the role of a "gauge" that adjusts edge weights without changing shortest paths.
The APSP problem has deep connections to matrix multiplication. Subramanian (1991) and later Williams (2018) showed that APSP can be solved faster than using techniques from fast matrix multiplication, though the improvements are sub-polynomial. Whether APSP requires time in the worst case (without fast matrix multiplication) remains open and is one of the central questions in fine-grained complexity theory [CLRS §25.2].
Bibliography Master
@book{clrs2022,
author = {Cormen, Thomas H. and Leiserson, Ronald L. and Rivest, Clifford and Stein, Christopher},
title = {Introduction to Algorithms},
edition = {4th},
publisher = {MIT Press},
year = {2022},
}
@article{floyd1962algorithm,
author = {Floyd, Robert W.},
title = {Algorithm 97: Shortest Path},
journal = {Communications of the ACM},
volume = {5},
number = {6},
pages = {345},
year = {1962},
}
@article{johnson1977efficient,
author = {Johnson, Donald B.},
title = {Efficient Algorithms for Shortest Paths in Sparse Networks},
journal = {Journal of the ACM},
volume = {24},
number = {1},
pages = {1--13},
year = {1977},
}