forked from TheAlgorithms/Python
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathscc_kosaraju.py
51 lines (43 loc) · 1.05 KB
/
scc_kosaraju.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
def dfs(u):
global g, r, scc, component, visit, stack
if visit[u]:
return
visit[u] = True
for v in g[u]:
dfs(v)
stack.append(u)
def dfs2(u):
global g, r, scc, component, visit, stack
if visit[u]:
return
visit[u] = True
component.append(u)
for v in r[u]:
dfs2(v)
def kosaraju():
global g, r, scc, component, visit, stack
for i in range(n):
dfs(i)
visit = [False] * n
for i in stack[::-1]:
if visit[i]:
continue
component = []
dfs2(i)
scc.append(component)
return scc
if __name__ == "__main__":
# n - no of nodes, m - no of edges
n, m = list(map(int, input().strip().split()))
g = [[] for i in range(n)] # graph
r = [[] for i in range(n)] # reversed graph
# input graph data (edges)
for i in range(m):
u, v = list(map(int, input().strip().split()))
g[u].append(v)
r[v].append(u)
stack = []
visit = [False] * n
scc = []
component = []
print(kosaraju())