Warshalls Algorithm
Warshalls Algorithm
Warshalls Algorithm
Overview:
Floyd-Warshall Algorithm, is a dynamic programming technique used for finding the
transitive closure of a directed graph. It determines the reachability between all pairs of
vertices in a graph, providing information about the accessibility of one vertex from
another.
Algorithm Steps:
1. Initialize the Distance Matrix:
Create a matrix representing the distance between vertices. Set
D
no direct edge.
2. Update the Distance Matrix:
Iterate through all vertices and update
k D[i][j] to be the minimum of and
D[i][j]
.
D[i][k] + D[k][j]
Example:
Consider the following directed graph:
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:
`Distance[i][j] = minimum (Distance[i][j], (Distance from i to A) + (Distance from A to j))
`Distance[i][j] = minimum (Distance[i][j], Distance[i][A] + Distance[A][j])
Step 3:
Treat node B as an intermediate node and calculate the Distance[][] for every {i,j} node
pair using the formula:
`Distance[i][j] = minimum (Distance[i][j], (Distance from i to B) + (Distance from B to j))
`Distance[i][j] = minimum (Distance[i][j], Distance[i][B] + Distance[B][j])
Step 4:
Treat node C as an intermediate node and calculate the Distance[][] for every {i,j} node
pair using the formula:
`Distance[i][j] = minimum (Distance[i][j], (Distance from i to C) + (Distance from C to j))
`Distance[i][j] = minimum (Distance[i][j], Distance[i][C] + Distance[C][j])
Step 5:
Treat node D as an intermediate node and calculate the Distance[][] for every {i,j} node
pair using the formula:
`Distance[i][j] = minimum (Distance[i][j], (Distance from i to D) + (Distance from D to j))
`Distance[i][j] = minimum (Distance[i][j], Distance[i][D] + Distance[D][j])
Step 6:
Treat node E as an intermediate node and calculate the Distance[][] for every {i,j} node
pair using the formula:
`Distance[i][j] = minimum (Distance[i][j], (Distance from i to E) + (Distance from E to j))
`Distance[i][j] = minimum (Distance[i][j], Distance[i][E] + Distance[E][j])
Step 7:
Since all the nodes have been treated as an intermediate node, we can now return the
updated Distance[][] matrix as our answer matrix.
Conclusion:
Warshall's Algorithm is a versatile method for determining the transitive closure of a
directed graph. It is particularly useful in applications where reachability between vertices
needs to be efficiently computed.