Skip to content

Commit b7ec18c

Browse files
author
I529010
committed
Added transitive closure with tests
1 parent b092045 commit b7ec18c

File tree

1 file changed

+48
-0
lines changed

1 file changed

+48
-0
lines changed

matrix/transitive_closure.py

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
def transitiveClosure(graph):
2+
"""
3+
Computes the transitive closure of a directed graph using the Floyd-Warshall algorithm.
4+
5+
Args:
6+
graph (list[list[int]]): Adjacency matrix representation of the graph.
7+
8+
Returns:
9+
list[list[int]]: Transitive closure matrix.
10+
11+
>>> graph = [
12+
... [0, 1, 1, 0],
13+
... [0, 0, 1, 0],
14+
... [1, 0, 0, 1],
15+
... [0, 0, 0, 0]
16+
... ]
17+
>>> result = transitiveClosure(graph)
18+
>>> for row in result:
19+
... print(row)
20+
[1, 1, 1, 1]
21+
[1, 1, 1, 1]
22+
[1, 1, 1, 1]
23+
[0, 0, 0, 1]
24+
"""
25+
n = len(graph)
26+
ans = [[graph[i][j] for j in range(n)] for i in range(n)]
27+
28+
# Transtive closure of (i, i) will always be 1
29+
for i in range(n):
30+
ans[i][i] = 1
31+
32+
# Apply floyd Warshall Algorithm
33+
# For each intermediate node k
34+
for k in range(n):
35+
for i in range(n):
36+
for j in range(n):
37+
38+
# Check if a path exists between i to k and
39+
# between k to j.
40+
if ans[i][k] == 1 and ans[k][j] == 1:
41+
ans[i][j] = 1
42+
43+
return ans
44+
45+
if __name__ == "__main__":
46+
import doctest
47+
48+
doctest.testmod()

0 commit comments

Comments
 (0)