Sometimes a relation lacks a property we want. The closure is the smallest relation that has the property and contains the original.
Closures
- Reflexive closure: add all missing (a, a) pairs.
- Symmetric closure: add (b, a) for every (a, b) in R.
- Transitive closure R⁺: add pairs until the relation is transitive. It tells you which elements are reachable by following one or more steps.
Example on {1, 2, 3} with R = {(1, 2), (2, 3)}:
- Reflexive closure: R ∪ {(1,1), (2,2), (3,3)}.
- Symmetric closure: R ∪ {(2,1), (3,2)}.
- Transitive closure: R ∪ {(1,3)}, since 1 → 2 → 3.
Warshall's algorithm
Warshall's algorithm finds the transitive closure using the matrix W of the relation. For each k = 1 to n in turn: for every row i with W[i][k] = 1, set row i = row i OR row k. After the last k, W is the transitive closure.
def warshall(W):
n = len(W)
for k in range(n):
for i in range(n):
for j in range(n):
W[i][j] = W[i][j] or (W[i][k] and W[k][j])
return W
print(warshall([[0, 1, 0], [0, 0, 1], [0, 0, 0]]))
Output:
[[0, 1, 1], [0, 0, 1], [0, 0, 0]]
Worked example
R = {(1, 2), (2, 3)} has matrix W₀ = rows [0 1 0], [0 0 1], [0 0 0].
- k = 1: no row has a 1 in column 1. No change.
- k = 2: row 1 has a 1 in column 2, so row 1 = row 1 OR row 2 = [0 1 1].
- k = 3: rows 1 and 2 have a 1 in column 3, but row 3 is all zeros. No change.
Result: rows [0 1 1], [0 0 1], [0 0 0], which adds the pair (1, 3).
The loop runs n times over an n × n matrix, so the running time is O(n³).
Why it matters
Transitive closure answers "can I get from A to B?" in networks, road maps, prerequisite chains and database queries about hierarchies.
Common mistakes
- Doing the k loop in the middle of the three loops. The k loop must be outermost.
- Stopping after one pass of pairs. A new pair can create more new pairs.
Practice questions
- Define reflexive, symmetric and transitive closures.
- Find the transitive closure of R = {(1, 2), (2, 3), (3, 4)} on {1, 2, 3, 4}.
- State Warshall's algorithm in words.
- What is the time complexity of Warshall's algorithm?
- Give one use of transitive closure.
Answers to the practice questions
- The smallest relation containing R that is reflexive, symmetric or transitive.
- R plus (1,3), (2,4) and (1,4).
- For each k in turn, for every row i with a 1 in column k, OR row k into row i.
- O(n³).
- Finding all reachable places in a network, or all ancestors in a hierarchy.
Sources
- Official BCA syllabus Mathematics Foundations to Computer Science I, course code CC101, Unit I
- Kolman, Busby and Ross, Discrete Mathematical Structures, 6th edition, Pearson
