Floyd Warshall
Floyd Warshall
The Floyd-Warshall algorithm, named after its creators Robert Floyd and Stephen Warshall, is a
fundamental algorithm in computer science and graph theory. It is used to find the shortest paths
between all pairs of nodes in a weighted graph. This algorithm is highly efficient and can handle graphs
with both positive and negative edge weights, making it a versatile tool for solving a wide range of
network and connectivity problems.
Obviously the shortest path between i to j will have some k number of intermediate nodes. The idea
behind floyd warshall algorithm is to treat each and every vertex from 1 to N as an intermediate node
one by one.
The following figure shows the above optimal substructure property in floyd warshall algorithm:
Step 1: Initialize the Distance[][] matrix using the input graph such that Distance[i][j]= weight of edge
from i to j, also Distance[i][j] = Infinity if there is no edge from i to j.
Step 2: Treat node A as an intermediate node and calculate the Distance[][] for every {i,j} node pair
using the formula:
Step 4: Treat node C as an intermediate node and calculate the Distance[][] for every {i,j} node pair
using the formula:
Step 6: Treat node E as an intermediate node and calculate the Distance[][] for every {i,j} node pair
using the formula:
// driver's code
int main()
{
/* Let us create the following weighted graph
10
(0)------->(3)
| /|\
5 | |
| | 1
\|/ |
(1)------->(2)
3
*/
int graph[V][V] = { { 0, 5, INF, 10 },
{ INF, 0, 3, INF },
{ INF, INF, 0, 1 },
{ INF, INF, INF, 0 } };
// Function call
floydWarshall(graph);
return 0;
}