Files
Python/matrix/transitive_closure.py
Deepak JainI529010Deepak14JainDeepak Jainpre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>Christian Clauss
ff206e632c Transitive Closure Algorithm (#12940)
* Added transitive closure with tests

* updating DIRECTORY.md

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* fix lint issue

* lint fix

* fix line_to_long issue

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* define return type

* added type hint

* fix line_too_long lint error

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* fix line_too_long

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Refactor transitive closure function for clarity

Updated parameter and return type annotations for clarity. Modified variable names for consistency and corrected comments.

* Refine docstring for transitive_closure function

Updated the docstring to improve clarity and fix grammar.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

---------

Co-authored-by: I529010 <deepak.jain04@sap.com>
Co-authored-by: Deepak14Jain <Deepak14Jain@users.noreply.github.com>
Co-authored-by: Deepak Jain <93066547+Deepak14Jain@users.noreply.github.com>
Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
Co-authored-by: Christian Clauss <cclauss@me.com>
2026-09-23 22:38:22 +02:00

53 lines
1.3 KiB
Python

"""
https://en.wikipedia.org/wiki/Transitive_closure#In_graph_theory
https://en.wikipedia.org/wiki/Floyd%E2%80%93Warshall_algorithm
"""
def transitive_closure(graph: list[list[int]]) -> list[list[int]]:
"""
Compute the transitive closure of a directed graph using the
Floyd-Warshall algorithm.
Args:
graph: Adjacency matrix representation of the graph.
Returns:
Transitive closure matrix.
>>> graph = [
... [0, 1, 1, 0],
... [0, 0, 1, 0],
... [1, 0, 0, 1],
... [0, 0, 0, 0]
... ]
>>> transitive_closure(graph) # doctest: +NORMALIZE_WHITESPACE
[[1, 1, 1, 1],
[1, 1, 1, 1],
[1, 1, 1, 1],
[0, 0, 0, 1]]
"""
width = len(graph)
ans = [[graph[i][j] for j in range(width)] for i in range(width)]
# Transitive closure of (i, i) will always be 1
for i in range(width):
ans[i][i] = 1
# Apply Floyd-Warshall Algorithm
# For each intermediate node k
for k in range(width):
for i in range(width):
for j in range(width):
# Check if a path exists from i to k and from k to j.
if ans[i][k] == 1 and ans[k][j] == 1:
ans[i][j] = 1
return ans
if __name__ == "__main__":
import doctest
doctest.testmod()