MCPcopy Create free account
hub / github.com/TheAlgorithms/Python / find_components

Function find_components

graphs/strongly_connected_components.py:37–56  ·  view source on GitHub ↗

Use depth first search to find strongly connected vertices. Now graph is reversed >>> find_components({0: [1], 1: [2], 2: [0]}, 0, 5 * [False]) [0, 1, 2] >>> find_components({0: [2], 1: [0], 2: [0, 1]}, 0, 6 * [False]) [0, 2, 1]

(
    reversed_graph: dict[int, list[int]], vert: int, visited: list[bool]
)

Source from the content-addressed store, hash-verified

35
36
37def find_components(
38 reversed_graph: dict[int, list[int]], vert: int, visited: list[bool]
39) -> list[int]:
40 """
41 Use depth first search to find strongly connected
42 vertices. Now graph is reversed
43 >>> find_components({0: [1], 1: [2], 2: [0]}, 0, 5 * [False])
44 [0, 1, 2]
45 >>> find_components({0: [2], 1: [0], 2: [0, 1]}, 0, 6 * [False])
46 [0, 2, 1]
47 """
48
49 visited[vert] = True
50 component = [vert]
51
52 for neighbour in reversed_graph[vert]:
53 if not visited[neighbour]:
54 component += find_components(reversed_graph, neighbour, visited)
55
56 return component
57
58
59def strongly_connected_components(graph: dict[int, list[int]]) -> list[list[int]]:

Callers 1

Calls

no outgoing calls

Tested by

no test coverage detected