forked from prabhupant/python-ds
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathkosaraju_algorithm.py
More file actions
88 lines (59 loc) · 1.74 KB
/
Copy pathkosaraju_algorithm.py
File metadata and controls
88 lines (59 loc) · 1.74 KB
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
"""
Reference - https://www.geeksforgeeks.org/strongly-connected-components/
Algorithm - https://youtu.be/RpgcYiky7uw
This is used to find all the strongly connected components and does DFS
2 times.
Note: A single vertex is also strongly connected
"""
from collections import defaultdict
class Graph:
def __init__(self, vertices):
self.vertices = vertices
self.graph = defaultdict(list)
def add_edge(self, u, v):
self.graph[u].append(v)
def fill_time(self, v, visited, stack):
visited[v] = True
for i in self.graph[v]:
if visited[i] == False:
self.fill_time(i, visited, stack)
stack = stack.append(v)
def dfs(self, v, visited):
visited[v] = True
print(v, end=' ')
for i in self.graph[v]:
if visited[i] == False:
self.dfs(i, visited)
def create_tranpose(self):
tgraph = Graph(self.vertices)
for i in self.graph:
for j in self.graph[i]:
tgraph.add_edge(j, i)
return tgraph
def kosaraju(self):
visited = [False] * self.vertices
stack = []
for v in range(self.vertices):
if visited[v] == False:
self.fill_time(v, visited, stack)
tgraph = self.create_tranpose()
visited = [False] * self.vertices
while stack:
s = stack.pop()
if visited[s] == False:
tgraph.dfs(s, visited)
print()
g = Graph(11)
g.add_edge(0, 1)
g.add_edge(2, 0)
g.add_edge(1, 2)
g.add_edge(1, 3)
g.add_edge(3, 4)
g.add_edge(4, 5)
g.add_edge(5, 3)
g.add_edge(6, 5)
g.add_edge(6, 7)
g.add_edge(7, 8)
g.add_edge(8, 9)
g.add_edge(9, 10)
g.kosaraju()