Sub topic 17
Floyd-Warshall All-Pairs Shortest Paths
Assume you know weighted graphs, adjacency matrices, dynamic programming, and the meaning of a shortest path. Floyd-Warshall computes the shortest distances between every pair of vertices. It works with directed or undirected graphs and allows negative edge weights, but not negative-weight cycles.
The dynamic programming idea
Number the vertices from 0 to n - 1. Let dist[i][j] be the shortest known distance from vertex i to vertex j.
Initially:
dist[i][i] = 0.dist[i][j]is the edge weight when an edge exists.dist[i][j]is infinity when no direct edge exists.
The algorithm considers vertices as possible intermediate vertices. After processing vertex k, dist[i][j] is the shortest path from i to j whose intermediate vertices come from 0 through k.
The recurrence is:
\[ dist[i][j] = \min(dist[i][j],\ dist[i][k] + dist[k][j]) \]
The loops must process k first. Changing the loop order can produce incorrect results.
def floyd_warshall(dist):
n = len(dist)
for k in range(n):
for i in range(n):
for j in range(n):
through_k = dist[i][k] + dist[k][j]
if through_k < dist[i][j]:
dist[i][j] = through_k
return dist
INF = float("inf")
graph = [
[0, 3, INF, INF],
[INF, 0, 1, INF],
[2, INF, 0, 4],
[INF, INF, INF, 0],
]
for row in floyd_warshall(graph):
print(row)The shortest distance from vertex 0 to vertex 3 becomes 8: the path is 0 → 1 → 2 → 3.
Complexity and negative cycles
| Property | Cost or rule |
|---|---|
| Time complexity | \(O(V^3)\) |
| Space complexity | \(O(V^2)\) |
| Negative edges | Allowed |
| Negative cycles | Detect using `dist[v][v] < 0` |
After the algorithm finishes, a negative value on the diagonal means that a negative-weight cycle is reachable from that vertex. A shortest path involving such a cycle is not well-defined because the cycle can be repeated to reduce the path cost without limit.
When to use Floyd-Warshall
Floyd-Warshall is useful when the graph is small or dense and many source-destination queries must be answered. After preprocessing, each distance query takes \(O(1)\) time.
For one source, Dijkstra is usually faster when all weights are non-negative. Bellman-Ford is better for one source when negative edges may exist. Floyd-Warshall is the direct choice when distances between all pairs are required.
Exercise
What does dist[i][i] < 0 indicate after Floyd-Warshall finishes?
Show answer
It indicates that vertex i can participate in, or reach, a negative-weight cycle, so shortest paths involving that cycle are unbounded below.