The Floyd–Warshall algorithm is an algorithm for finding shortest paths in a weighted graph with positive or negative edge weights (but with no negative cycles). It computes the shortest paths between all pairs of vertices in a single execution.
History and Naming The algorithm is named after Robert Floyd and Stephen Warshall, who published their respective versions in 1962. Bernard Roy also discovered the algorithm independently in 1959. It is sometimes referred to as the Roy–Floyd algorithm or the Roy–Warshall algorithm.
Algorithm Description The algorithm uses dynamic programming. It considers the vertices of the graph one by one, updating the shortest path estimates between all pairs of vertices to allow the use of the currently considered vertex as an intermediate point.
Let $dist[i][j]$ represent the shortest distance from vertex $i$ to vertex $j$. The algorithm initializes $dist$ with the direct edge weights (or infinity if no direct edge exists, and 0 for $i=j$). Then, for each intermediate vertex $k$ from 1 to $V$ (where $V$ is the number of vertices), it performs the relaxation step: $$dist[i][j] = \min(dist[i][j], dist[i][k] + dist[k][j])$$
Complexity
- Time Complexity: $\Theta(V^3)$, where $V$ is the number of vertices. This is due to the three nested loops over the vertex set.
- Space Complexity: $\Theta(V^2)$ to store the distance matrix.
Applications and Properties
- All-Pairs Shortest Path: It is the standard algorithm for dense graphs where shortest paths between all pairs are required.
- Negative Weights: It handles negative edge weights correctly, provided the graph contains no negative-weight cycles reachable from the source.
- Negative Cycle Detection: The algorithm can detect negative cycles by checking if $dist[v][v] < 0$ for any vertex $v$ after execution.
- Transitive Closure: A variation of the algorithm (Warshall's algorithm) computes the transitive closure of a boolean graph (reachability) using logical operations (OR/AND) instead of arithmetic (min/+).
- Path Reconstruction: With minor modifications (storing a "next" or "predecessor" matrix), the actual paths can be reconstructed, not just their lengths.
Comparison For sparse graphs (where the number of edges $E$ is much less than $V^2$), running Dijkstra's algorithm from each vertex (with a Fibonacci heap) has a complexity of $O(VE + V^2 \log V)$, which is asymptotically faster than Floyd–Warshall. For dense graphs, Floyd–Warshall is often preferred due to its simplicity, low constant factors, and cache efficiency.