Warshall's Algorithm
Warshall's Algorithm
Floyd-Warshall is a dynamic programming algorithm used to solve all pair shortest path
problems. This algorithm is different from other shortest path algorithms; to describe it
simply, this algorithm uses each vertex in the graph as a pivot to check if it provides the
shortest way to travel from one point to another.
Floyd-Warshall algorithm works on both 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). It follows Dynamic Programming approach to check every possible path going
via every possible node in order to calculate shortest distance between every pair of nodes.
Algorithm
Consider a graph, G = {V, E} where V is the set of all vertices present in the graph and E is
the set of all the edges in the graph. The graph, G, is represented in the form of an adjacency
matrix, A, that contains all the weights of every edge connecting two vertices.
Step 1 − Construct an adjacency matrix A with all the costs of edges present in the graph. If
there is no path between two vertices, mark the value as ∞.
Step 2 − Derive another adjacency matrix A1 from A keeping the first row and first column
of the original adjacency matrix intact in A1. And for the remaining values, say A1[i,j],
if A[i,j]>A[i,k]+A[k,j] then replace A1[i,j] with A[i,k]+A[k,j]. Otherwise, do not change the
values. Here, in this step, k = 1 (first vertex acting as pivot).
Step 3 − Repeat Step 2 for all the vertices in the graph by changing the k value for every
pivot vertex until the final matrix is achieved.
Step 4 − The final adjacency matrix obtained is the final solution with all the shortest paths.
Pseudocode
n = no of vertices
D = matrix of dimension n*n
for k = 1 to n
for i = 1 to n
for j = 1 to n
Dk[i, j] = min (Dk-1[i, j], Dk-1[i, k] + Dk-1[k, j])
return D
Make the distance matrix or graph matrix. Insert the distance value and if the distance is
unknown fill that with ∞.
D0 =
A B C D
A 0 6 5 ∞
B 3 0 ∞ 2
C ∞ 4 0 ∞
D ∞ ∞ 7 0
Now calculating the Distance of every pair Via A.
DA =
A B C D
A 0 6 5 ∞
B 3
C ∞
D ∞
A B C D
A 0 6 5 ∞
B 3 0 8 2
C ∞ 4 0 ∞
D ∞ ∞ 7 0
Now calculating the Distance of every pair Via B
DB =
A B C D
A 6
B 3 0 8 2
C 4
D ∞
A B C D
A 0 6 5 8
B 3 0 8 2
C 7 4 0 6
D ∞ ∞ 7 0
Now, calculating distance of each path via C.
DC =
A B C D
A 5
B 8
C 7 4 0 6
D 7
A B C D
A 0 6 5 8
B 3 0 8 2
C 7 4 0 6
D 14 11 7 0
Similarly, if we calculate the shortest distance Via D, No changes will be required
Hence, the shortest path matrix using Floyd’s Warshall algorithm is as follows:
A B C D
A 0 6 5 8
B 3 0 8 2
C 7 4 0 6
D 14 11 7 0
Application
In networking devices