Floyd-Warshall Algorithm
The Floyd-Warshall algorithm is an algorithm that finds the shortest paths between all pairs of vertices in a graph. It can be used on graphs with negative weights. It can also be used on graphs with negative cycles. It is implemented using dynamic programming.
Recurrence Relation
D_{ij} = min(D_{ij}, D_{ik} + D_{kj})
Procedure
- Initialize a 2D array.
- Iterate through all the vertices using three nested loops.
- Update the shortest paths using the recurrence relation.
Example Code
|
|
Advantages
- It can be used to find the shortest paths between all pairs of vertices.
- It can be used on graphs with negative weights.
Disadvantages
- It is slower than Dijkstra’s algorithm for finding the shortest path from one vertex to another.
- It cannot find the shortest paths if the graph contains a negative cycle.
Time Complexity
- The Floyd-Warshall algorithm has a time complexity of
O(n^3)
where n is the number of vertices.