Warshal Algorithm
Warshal Algorithm
Vertex A B C D E F G
B 3 1 D
Status 0 0 0 0 0 1 0
Dist. 0 3 2 1 2 1 1
1 G Next * A B C D G E
A 0 2 2
E
C
1 F
Step 7:
Vertex A B C D E F G
B 3 1 D
Status 0 0 0 0 0 0 0
Dist. 0 3 2 1 2 1 1
2 E
A 0 2 1 G Next * A B C D G E
C 1 F
Warshall’s algorithm requires knowing which edges exist and which does not. It doesn’t
need to know the lengths of the edges in the given directed graph. This information is
conveniently displayed by adjacency matrix for the graph, in which a ‘1’ indicates the
existence of an edge and ‘0’ indicates non-existence.
A l l P a ir s Re c h a b i l it y
A d j ac e nc y M at r i x W a r s h a ll’ s A l g or it h m
M at r i x
It begins with the adjacency matrix for the given graph, which is called A0, and then
updates the matrix ‘n’ times, producing matrices called A1, A2, . . . . . , An and then
stops.
A one entry indicates a pair of vertices, which are connected and zero entry indicates a
pair, which are not. This matrix is called a reachability matrix or path matrix for the
graph. It is also called the transitive closure of the original adjacency matrix.
The update rule for computing Ai from Ai-1 in warshall’s algorithm is:
Ai [x, y] = Ai-1 [x, y] (Ai-1 [x, i] Ai-1 [i, y]) ---- (1)
Use warshall’s algorithm to calculate the reachability matrix for the graph:
4
1 4
5 6
7 11
1
2 3
7
1 0 1 1 0
2 0 0 1 1
A0
3 0 0 0 0
4 1 1 1 0
The first step is to compute ‘A1’ matrix. To do so we will use the updating rule – (1).
Before doing so, we notice that only one entry in A0 must remain one in A1, since in
Boolean algebra 1 + (anything) = 1. Since these are only nine zero entries in A0, there
are only nine entries in A0 that need to be updated.
1 0 1 1 0
2 0 0 1 1
A1
3 0 0 0 0
4 1 1 1 0
Next, A2 must be calculated from A1; but again we need to update the 0 entries,
1 0 1 1 1
2 0 0 1 1
A2
3 0 0 0 0
4 1 1 1 1
This matrix has only seven 0 entries, and so to compute A3, we need to do only seven
computations.
1 0 1 1 1
2 0 0 1 1
A3
3 0 0 0 0
4 1 1 1 1
Once A3 is calculated, we use the update rule to calculate A4 and stop. This matrix is
the reachability matrix for the graph.
1 1 1 1 1
2 1 1 1 1
A4
3 0 0 0 0
4 1 1 1 1
Note that according to the algorithm vertex 3 is not reachable from itself 1. This is
because as can be seen in the graph, there is no path from vertex 3 back to itself.