File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change 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 ()
You can’t perform that action at this time.
0 commit comments