Skip to content

Commit 2fb4e81

Browse files
authored
Refactor transitive closure function for clarity
Updated parameter and return type annotations for clarity. Modified variable names for consistency and corrected comments.
1 parent d0e0116 commit 2fb4e81

1 file changed

Lines changed: 16 additions & 19 deletions

File tree

‎matrix/transitive_closure.py‎

Lines changed: 16 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -4,39 +4,36 @@ def transitive_closure(graph: list[list[int]]) -> list[list[int]]:
44
Floyd-Warshall algorithm.
55
66
Args:
7-
graph (list[list[int]]): Adjacency matrix representation of the graph.
7+
graph: Adjacency matrix representation of the graph.
88
99
Returns:
10-
list[list[int]]: Transitive closure matrix.
10+
Transitive closure matrix.
1111
1212
>>> graph = [
1313
... [0, 1, 1, 0],
1414
... [0, 0, 1, 0],
1515
... [1, 0, 0, 1],
1616
... [0, 0, 0, 0]
1717
... ]
18-
>>> result = transitive_closure(graph)
19-
>>> for row in result:
20-
... print(row)
21-
[1, 1, 1, 1]
22-
[1, 1, 1, 1]
23-
[1, 1, 1, 1]
24-
[0, 0, 0, 1]
18+
>>> transitive_closure(graph) # doctest: +NORMALIZE_WHITESPACE
19+
[[1, 1, 1, 1],
20+
[1, 1, 1, 1],
21+
[1, 1, 1, 1],
22+
[0, 0, 0, 1]]
2523
"""
26-
n = len(graph)
27-
ans = [[graph[i][j] for j in range(n)] for i in range(n)]
24+
width = len(graph)
25+
ans = [[graph[i][j] for j in range(width)] for i in range(width)]
2826

29-
# Transtive closure of (i, i) will always be 1
30-
for i in range(n):
27+
# Transitive closure of (i, i) will always be 1
28+
for i in range(width):
3129
ans[i][i] = 1
3230

33-
# Apply floyd Warshall Algorithm
31+
# Apply Floyd-Warshall Algorithm
3432
# For each intermediate node k
35-
for k in range(n):
36-
for i in range(n):
37-
for j in range(n):
38-
# Check if a path exists between i to k and
39-
# between k to j.
33+
for k in range(width):
34+
for i in range(width):
35+
for j in range(width):
36+
# Check if a path exists from i to k and from k to j.
4037
if ans[i][k] == 1 and ans[k][j] == 1:
4138
ans[i][j] = 1
4239

0 commit comments

Comments
 (0)