Warshall Algorithm
Warshall Algorithm
1
Relational closures
• Three types we will study
– Reflexive
• Easy
– Symmetric
• Easy
– Transitive
• Hard
2
Reflexive closure
• Consider a relation R:
(Note that it is not reflexive)
4
Example:
• Let R be a relation on the set { 0, 1, 2, 3 } containing the
ordered pairs (0,1), (1,1), (1,2), (2,0), (2,2), and (3,0)
• What is the reflexive closure of R?
• We add all pairs of edges (a,a) that do not already exist
0 1
We add edges:
(0,0), (3,3)
3 2
5
Symmetric closure
• Consider a relation R:
(Note that it is not symmetric)
7
Example:
• Let R be a relation on the set { 0, 1, 2, 3 } containing the
ordered pairs (0,1), (1,1), (1,2), (2,0), (2,2), and (3,0)
• What is the symmetric closure of R?
• We add all pairs of edges (a,b) where (b,a) exists
– We make all “single” edges into anti-parallel pairs
0 1
We add edges:
(0,2), (0,3)
(1,0), (2,1)
3 2
8
Paths in directed graphs
• A path is a sequences of connected edges from vertex a
to vertex b
End (b)
• A path that starts and
ends at the same
vertex is called a Start (a)
circuit or cycle End (b)
– Must have length ≥1
9
Start (a)
More on paths…
• The length of a path is the number of
edges in the path, not the number of
nodes
10
Shortest paths
• What is really needed in most applications
is finding the shortest path between two
vertices
11
Transitive closure
The transitive closure would
contain edges between all nodes
reachable by a path of any length
12
Transitive closure
• Informal definition: If there is a path from a to b, then
there should be an edge from a to b in the transitive
closure
• First take of a definition:
– In order to find the transitive closure of a relation R, we add an
edge from a to c, when there are edges from a to b and b to c
• But there is a path from 1 to 4 with no edge!
(1,2) & (2,3) (1,3)
R = { (1,2), (2,3), (3,4) } 4 (2,3) & (3,4) (2,4)
4
1 1
2 3 2 3
13
Transitive closure
• Informal definition: If there is a path from a to b, then
there should be an edge from a to b in the transitive
closure
18
Example:
• Find the zero-one matrix of the transitive
closure of the relation R given by:
1 0 1 1 2 1 2
M R 0 1 0
1 1 0 M [R2 ]
3 3
M R* M R M [ 2]
R M [ 3]
R
1 0 1 1 0 1 1 1 1
M [R2] M R M R 0 1 0 0 1 0 0 1 0
1 1 0 1 1 0 1 1 1
19
1 1 1 1 0 1 1 1 1
M [R3] M [R2 ] M R 0 1 0 0 1 0 0 1 0
1 1 1 1 1 0 1 1 1
1 2
1 0 1 1 1 1 1 1 1 1 1 1
M R* 0 1 0 0 1 0 0 1 0 0 1 0
1 1 0 1 1 1 1 1 1 1 1 1 20
Transitive closure algorithm
• What we did (or rather, could have done):
– Compute the next matrix M[iR], where 1 ≤ i ≤ n
– Do a Boolean join with the previously
computed matrix
• For example:
– Compute M[R2] M R M R
– Join that with M R to yield M R M[R2 ]
– Compute M R M R M R
[ 3] [ 2]
24
Example: R={(1, 2), (1, 3), (2, 3), (3, 4) }.
25
26
Example:
27