Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
Download

📚 The CoCalc Library - books, templates and other resources

132940 views
License: OTHER
1
def strongly_connected_components(graph):
2
index_counter = 0
3
stack = []
4
lowlinks = {}
5
index = {}
6
result = []
7
8
def strongconnect(node, index_counter):
9
index[node] = index_counter
10
lowlinks[node] = index_counter
11
index_counter += 1
12
stack.append(node)
13
14
try:
15
successors = graph[node]
16
except:
17
successors = []
18
19
# Depth first search
20
for successor in successors:
21
# Does the current node point to a node that was already
22
# visited?
23
if successor not in lowlinks:
24
# Successor has not yet been visited; recurse on it
25
strongconnect(successor, index_counter)
26
lowlinks[node] = min(lowlinks[node], lowlinks[successor])
27
elif successor in stack:
28
# the successor is in the stack and hence in the
29
# current strongly connected component (SCC)
30
lowlinks[node] = min(lowlinks[node], index[successor])
31
32
# If `node` is a root node, pop the stack and generate an SCC
33
if lowlinks[node] == index[node]:
34
connected_component = []
35
36
while True:
37
successor = stack.pop()
38
connected_component.append(successor)
39
if successor == node:
40
break
41
42
component = tuple(connected_component)
43
44
# storing the result
45
result.append(component)
46
47
for node in graph:
48
if node not in lowlinks:
49
strongconnect(node, index_counter)
50
51
return result
52
53