Warshalls Floyds Algorithm
Warshalls Floyds Algorithm
Warshalls Floyds Algorithm
Dr. Ying Lu
[email protected]
1
Warshall’s algorithm: transitive closure
• Computes the transitive closure of a relation
• (Alternatively: all paths in a directed graph)
3 3
1 1
4 4 0 0 1 0
2 0 0 1 0 2
1 0 0 1 1 1 1 1
0 0 0 0 0 0 0 0
0 1 0 0 1 1 1 1
2
Warshall’s algorithm
• Main idea: a path exists between two vertices i, j, iff
•there is an edge from i to j; or
•…
3
Warshall’s algorithm
• Main idea: a path exists between two vertices i, j, iff
•there is a path from i to j going through intermediate
vertices which are drawn from set {vertex 1, 2, … k-1}; or
•...
4
Warshall’s algorithm
P1
i j
p2
• For any pair of vertices i, j: Rn[i, j], that is Rn
• Starting with R0=A, the adjacency matrix, how to get R1 …
Rk-1 Rk … Rn
5
Warshall’s algorithm
k Vk
Vk-1
p
i j
6
Warshall’s algorithm
p
k Vk
p1
Vk-1 p2
i j
7
Warshall’s algorithm
i j
8
Warshall’s algorithm
{
R(k)[i,j] =
R(k-1)[i,j]
or
(path using just 1, …, k-1)
j
9
Warshall’s algorithm
3
3 1
1
2 4
2 4 3 R2
R1 1 0 0 1 0
R0
0 0 1 0 0 0 1 0 1 0 1 1
1 0 0 1 1 0 1 1 0 0 0 0
2 4 1 1 1 1
0 0 0 0 0 0 0 0
0 1 0 0 0 1 0 0
3 R4
3 R3 1
1 0 0 1 0 0 0 1 0
1 0 1 1 1 1 1 1
0 0 0 0 4 0 0 0 0
2 1 1 1 1
2 4 1 1 1 1
10
Warshall’s algorithm
R0 = A R1 R2
0 0 1 0 0 0 1 0 0 0 1 0
1 0 0 1 1 0 1 1 1 0 1 1
0 0 0 0 0 0 0 0 0 0 0 0
0 1 0 0 0 1 0 0 1 1 1 1
R3 R4
0 0 1 0 0 0 1 0
1 0 1 1 1 1 1 1
0 0 0 0 0 0 0 0
1 1 1 1 1 1 1 1
11
In-class exercises
Apply Warshall’s algorithm to find the transitive closure of
the digraph defined by the following adjacency matrix
0 1 0 0
0 0 1 0
0 0 0 1
0 0 0 0
12