- Notifications
You must be signed in to change notification settings - Fork 46.7k
/
Copy pathstrongly_connected_components.py
90 lines (67 loc) · 2.44 KB
/
strongly_connected_components.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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
"""
https://en.wikipedia.org/wiki/Strongly_connected_component
Finding strongly connected components in directed graph
"""
test_graph_1= {0: [2, 3], 1: [0], 2: [1], 3: [4], 4: []}
test_graph_2= {0: [1, 2, 3], 1: [2], 2: [0], 3: [4], 4: [5], 5: [3]}
deftopology_sort(
graph: dict[int, list[int]], vert: int, visited: list[bool]
) ->list[int]:
"""
Use depth first search to sort graph
At this time graph is the same as input
>>> topology_sort(test_graph_1, 0, 5 * [False])
[1, 2, 4, 3, 0]
>>> topology_sort(test_graph_2, 0, 6 * [False])
[2, 1, 5, 4, 3, 0]
"""
visited[vert] =True
order= []
forneighbouringraph[vert]:
ifnotvisited[neighbour]:
order+=topology_sort(graph, neighbour, visited)
order.append(vert)
returnorder
deffind_components(
reversed_graph: dict[int, list[int]], vert: int, visited: list[bool]
) ->list[int]:
"""
Use depth first search to find strongly connected
vertices. Now graph is reversed
>>> find_components({0: [1], 1: [2], 2: [0]}, 0, 5 * [False])
[0, 1, 2]
>>> find_components({0: [2], 1: [0], 2: [0, 1]}, 0, 6 * [False])
[0, 2, 1]
"""
visited[vert] =True
component= [vert]
forneighbourinreversed_graph[vert]:
ifnotvisited[neighbour]:
component+=find_components(reversed_graph, neighbour, visited)
returncomponent
defstrongly_connected_components(graph: dict[int, list[int]]) ->list[list[int]]:
"""
This function takes graph as a parameter
and then returns the list of strongly connected components
>>> strongly_connected_components(test_graph_1)
[[0, 1, 2], [3], [4]]
>>> strongly_connected_components(test_graph_2)
[[0, 2, 1], [3, 5, 4]]
"""
visited=len(graph) * [False]
reversed_graph: dict[int, list[int]] = {vert: [] forvertinrange(len(graph))}
forvert, neighboursingraph.items():
forneighbourinneighbours:
reversed_graph[neighbour].append(vert)
order= []
fori, was_visitedinenumerate(visited):
ifnotwas_visited:
order+=topology_sort(graph, i, visited)
components_list= []
visited=len(graph) * [False]
foriinrange(len(graph)):
vert=order[len(graph) -i-1]
ifnotvisited[vert]:
component=find_components(reversed_graph, vert, visited)
components_list.append(component)
returncomponents_list