Floyd Warshall
Floyd-Warshall algorithm is an algorithm for finding the shorted paths between all pairs of vertices in a weighted directed graph with positive or negative edge weights (but no negative cycles).
Floyd-Warshall algorithm and Bellman-Ford algorithm are both DP algorithms. Floyd-Warshall tries every vertice for each pair of vertices to find the shortest path between the vertice pair, while Bellman-Ford tries every edge V-1
times to find the shortest path between a specific source node to all other nodes.
Algorithm
For each vertice n
, try to use it to update the min distance between each vertice pair u, v
.
The time complexity is O(V^3)
. The space complexity is O(V^2)
.
The following is the Floyd-Warshall algorithm application on 1334. Find the City With the Smallest Number of Neighbors at a Threshold Distance (Medium).
The distances are initialized as 1e6
because there are at most 100 nodes and each edge at most weights 10^4
, so the maximum path weight won't exceed 10^6
.
Path reconstruction
The Floyd-Warshall algorithm typically only provides the lengths of the paths between all pairs of vertices. We can nodify it to reconstruct the path for between any two endpoint vertices.
Problems
Reference
Last updated