Python/graphs/scc_kosaraju.py

52 lines
1.0 KiB
Python
Raw Normal View History

2018-10-19 12:48:28 +00:00
def dfs(u):
global g, r, scc, component, visit, stack
2019-10-05 05:14:13 +00:00
if visit[u]:
return
2018-10-19 12:48:28 +00:00
visit[u] = True
for v in g[u]:
dfs(v)
stack.append(u)
2019-10-05 05:14:13 +00:00
2018-10-19 12:48:28 +00:00
def dfs2(u):
global g, r, scc, component, visit, stack
2019-10-05 05:14:13 +00:00
if visit[u]:
return
2018-10-19 12:48:28 +00:00
visit[u] = True
component.append(u)
for v in r[u]:
dfs2(v)
2019-10-05 05:14:13 +00:00
2018-10-19 12:48:28 +00:00
def kosaraju():
global g, r, scc, component, visit, stack
for i in range(n):
dfs(i)
2019-10-05 05:14:13 +00:00
visit = [False] * n
2018-10-19 12:48:28 +00:00
for i in stack[::-1]:
2019-10-05 05:14:13 +00:00
if visit[i]:
continue
2018-10-19 12:48:28 +00:00
component = []
dfs2(i)
scc.append(component)
return scc
if __name__ == "__main__":
# n - no of nodes, m - no of edges
2019-10-05 05:14:13 +00:00
n, m = list(map(int, input().strip().split()))
2019-10-05 05:14:13 +00:00
g = [[] for i in range(n)] # graph
r = [[] for i in range(n)] # reversed graph
# input graph data (edges)
for i in range(m):
2019-10-05 05:14:13 +00:00
u, v = list(map(int, input().strip().split()))
g[u].append(v)
r[v].append(u)
stack = []
2019-10-05 05:14:13 +00:00
visit = [False] * n
scc = []
component = []
print(kosaraju())