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

Function tarjan

graphs/tarjans_scc.py:4–80  ·  view source on GitHub ↗

Tarjan's algo for finding strongly connected components in a directed graph Uses two main attributes of each node to track reachability, the index of that node within a component(index), and the lowest index reachable from that node(lowlink). We then perform a dfs of the each comp

(g: list[list[int]])

Source from the content-addressed store, hash-verified

2
3
4def tarjan(g: list[list[int]]) -> list[list[int]]:
5 """
6 Tarjan's algo for finding strongly connected components in a directed graph
7
8 Uses two main attributes of each node to track reachability, the index of that node
9 within a component(index), and the lowest index reachable from that node(lowlink).
10
11 We then perform a dfs of the each component making sure to update these parameters
12 for each node and saving the nodes we visit on the way.
13
14 If ever we find that the lowest reachable node from a current node is equal to the
15 index of the current node then it must be the root of a strongly connected
16 component and so we save it and it's equireachable vertices as a strongly
17 connected component.
18
19 Complexity: strong_connect() is called at most once for each node and has a
20 complexity of O(|E|) as it is DFS.
21 Therefore this has complexity O(|V| + |E|) for a graph G = (V, E)
22
23 >>> tarjan([[2, 3, 4], [2, 3, 4], [0, 1, 3], [0, 1, 2], [1]])
24 [[4, 3, 1, 2, 0]]
25 >>> tarjan([[], [], [], []])
26 [[0], [1], [2], [3]]
27 >>> a = [0, 1, 2, 3, 4, 5, 4]
28 >>> b = [1, 0, 3, 2, 5, 4, 0]
29 >>> n = 7
30 >>> sorted(tarjan(create_graph(n, list(zip(a, b))))) == sorted(
31 ... tarjan(create_graph(n, list(zip(a[::-1], b[::-1])))))
32 True
33 >>> a = [0, 1, 2, 3, 4, 5, 6]
34 >>> b = [0, 1, 2, 3, 4, 5, 6]
35 >>> sorted(tarjan(create_graph(n, list(zip(a, b)))))
36 [[0], [1], [2], [3], [4], [5], [6]]
37 """
38
39 n = len(g)
40 stack: deque[int] = deque()
41 on_stack = [False for _ in range(n)]
42 index_of = [-1 for _ in range(n)]
43 lowlink_of = index_of[:]
44
45 def strong_connect(v: int, index: int, components: list[list[int]]) -> int:
46 index_of[v] = index # the number when this node is seen
47 lowlink_of[v] = index # lowest rank node reachable from here
48 index += 1
49 stack.append(v)
50 on_stack[v] = True
51
52 for w in g[v]:
53 if index_of[w] == -1:
54 index = strong_connect(w, index, components)
55 lowlink_of[v] = (
56 lowlink_of[w] if lowlink_of[w] < lowlink_of[v] else lowlink_of[v]
57 )
58 elif on_stack[w]:
59 lowlink_of[v] = (
60 lowlink_of[w] if lowlink_of[w] < lowlink_of[v] else lowlink_of[v]
61 )

Callers 1

tarjans_scc.pyFile · 0.85

Calls 1

strong_connectFunction · 0.85

Tested by

no test coverage detected