-
Notifications
You must be signed in to change notification settings - Fork 74
/
Copy pathstrongly_connected.py
59 lines (45 loc) · 1.33 KB
/
strongly_connected.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
52
53
54
55
56
57
58
59
# Uses python3
import sys
sys.setrecursionlimit(200000)
def reverse_graph(adj):
reverse_adj = [[] for _ in range(len(adj))]
for vertex in range(len(adj)):
for adj_vertex in adj[vertex]:
reverse_adj[adj_vertex].append(vertex)
return reverse_adj
def number_of_strongly_connected_components(adj):
result = 0
visited = [False] * len(adj)
finish_order = []
def explore(v):
visited[v] = True
for u in adj[v]:
if not visited[u]:
explore(u)
finish_order.append(v)
def explore_reverse(v):
visited[v] = True
for u in adj[v]:
if not visited[u]:
explore(u)
for v in range(len(adj)):
if not visited[v]:
explore(v)
adj = reverse_graph(adj)
visited = [False] * len(adj)
while finish_order:
v = finish_order.pop()
if not visited[v]:
explore_reverse(v)
result += 1
return result
if __name__ == '__main__':
user_input = sys.stdin.read()
data = list(map(int, user_input.split()))
n, m = data[0:2]
data = data[2:]
edges = list(zip(data[0:(2 * m):2], data[1:(2 * m):2]))
adj = [[] for _ in range(n)]
for (a, b) in edges:
adj[a - 1].append(b - 1)
print(number_of_strongly_connected_components(adj))