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
65 lines (41 loc) · 1.36 KB
/
kosaraju_algorithm.py
File metadata and controls
65 lines (41 loc) · 1.36 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
# Reference - https://www.geeksforgeeks.org/strongly-connected-components/
# This is used to find all the strongly connected components and does DFS
# 2 times.
from collections import defaultdict
class Graph:
def __init__(self, vertices):
self.V = vertices
self.graph = defaultdict(list)
def add_edge(self, u, v):
self.graph[u].append(v)
def dfs_util(self, v, visited):
visited[v] = True
print(v, end=' ')
for i in self.graph[v]:
if visited[i] == False:
self.dfs_util(i, visited)
def fill_order(self, v, visited, stack):
visited[v] = True
for i in self.graph[v]:
if visited[i] == False:
self.fill_order(i, visited, stack)
stack.append(v)
def get_transpose(self):
g = Graph(self.V)
for i in self.graph:
for j in self.graph[i]:
g.add_edge(j, i)
return g
def kosaraju(self):
stack = []
visited = [False] * self.V
for i in range(self.V):
if visited[i] == False:
self.fill_order(i, visited, stack)
gr = self.get_transpose()
visited = [False] * self.V
while stack:
i = stack.pop()
if visited[i] == False:
gr.dfs_util(i, visited)
print()