Algorithm 97 (Shortest Path) / Floyd-Warshall Algorithm
Citation: Floyd, R. W. (1962). Algorithm 97: Shortest Path. Communications of the ACM, 5(6), 345.
Core Contribution
Published the Floyd-Warshall algorithm for finding shortest paths in weighted graphs. Also established the invariant assertion method for proving correctness of programs — proving that the algorithm maintains a loop invariant rather than trying to prove the final result directly.
Key Concepts
- Dynamic programming: Break problem into overlapping subproblems
- Path matrix: dp[k][i][j] = shortest path from i to j using only vertices 0..k
- Loop invariant: At each iteration k, dp[i][j] = shortest path using vertices in {0..k}
- Transitive closure: Extends to reachability problems
Invariant Assertion Method
Floyd’s paper established the pattern of:
- Define the loop invariant
- Prove invariant holds initially (base case)
- Prove invariant preserved by loop body
- Use invariant to prove correctness after loop
This is now standard for proving algorithm correctness.
Time Complexity
- O(V³) where V = number of vertices
- Worse than Dijkstra for single-source (O(E log V)) on sparse graphs
- Better than repeated Dijkstra for all-pairs shortest path on dense graphs
Floyd-Warshall Code
def floyd_warshall(graph):
dist = graph.copy() # adjacency matrix
n = len(dist)
for k in range(n):
for i in range(n):
for j in range(n):
if dist[i][k] + dist[k][j] < dist[i][j]:
dist[i][j] = dist[i][k] + dist[k][j]
return distSee Also
- Data Structures (graphs)
- Algorithms (shortest path, dynamic programming)