Floyd
Floyd
Floyd-Warshall Algorithm is an algorithm for finding the shortest path between all
the pairs of vertices in a weighted graph. This algorithm works for both the
directed and undirected weighted graphs. But, it does not work for the graphs with
negative cycles (where the sum of the edges in a cycle is negative).
A weighted graph is a graph in which each edge has a numerical value associated
with it.
Initial graph
Follow the steps below to find the shortest path between all the pairs of vertices.
Each cell A[i][j] is filled with the distance from the ith vertex to the jth
vertex. If there is no path from ith vertex to jth vertex, the cell is left as
infinity.
Fill each cell with the distance between ith and jth vertex
2. Now, create a matrix A1 using matrix A0. The elements in the first column
and the first row are left as they are. The remaining cells are filled in the
following way.
That is, if the direct distance from the source to the destination is greater
than the path through the vertex k, then the cell is filled with A[i][k] +
A[k][j].
3. Similarly, A2 is created using A1. The elements in the second column and the
second row are left as they are.
In this step, k is the second vertex (i.e. vertex 2). The remaining steps are the
same as in step 2.
Calculate the distance from the source vertex to destination vertex through
this vertex 2
4. Similarly, A3 and A4 is also created.
5. Calculate the distance from the source vertex to destination vertex through
this vertex 3
6. Calculate the distance from the source vertex to destination vertex through
this vertex 4
7. A4 gives the shortest path between each pair of vertices.
Floyd-Warshall Algorithm
n = no of vertices
A = matrix of dimension n*n
for k = 1 to n
for i = 1 to n
for j = 1 to n
Ak[i, j] = min (Ak-1[i, j], Ak-1[i, k] + Ak-1[k, j])
return A