Python/graphs/scc_kosaraju.py

55 lines
1.3 KiB
Python
Raw Normal View History

from __future__ import annotations
2021-07-06 07:08:33 +00:00
2018-10-19 12:48:28 +00:00
def dfs(u):
2021-07-06 07:08:33 +00:00
global graph, reversedGraph, 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
2021-07-06 07:08:33 +00:00
for v in graph[u]:
2018-10-19 12:48:28 +00:00
dfs(v)
stack.append(u)
2019-10-05 05:14:13 +00:00
2018-10-19 12:48:28 +00:00
def dfs2(u):
2021-07-06 07:08:33 +00:00
global graph, reversedGraph, 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)
2021-07-06 07:08:33 +00:00
for v in reversedGraph[u]:
2018-10-19 12:48:28 +00:00
dfs2(v)
2019-10-05 05:14:13 +00:00
2018-10-19 12:48:28 +00:00
def kosaraju():
2021-07-06 07:08:33 +00:00
global graph, reversedGraph, scc, component, visit, stack
2018-10-19 12:48:28 +00:00
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()))
graph: list[list[int]] = [[] for i in range(n)] # graph
reversedGraph: list[list[int]] = [[] 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()))
2021-07-06 07:08:33 +00:00
graph[u].append(v)
reversedGraph[v].append(u)
stack: list[int] = []
visit: list[bool] = [False] * n
scc: list[int] = []
component: list[int] = []
print(kosaraju())