-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathscc_graph.py
75 lines (62 loc) · 2 KB
/
scc_graph.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
# Algorthms GUI Project / scc_graph.py
# Created on: 07-Nov-2018
# Author: Gourav Siddhad
# Kosaraju's algorithm / Strongly Connected Components
from collections import defaultdict
class SCC_Graph:
def __init__(self, vertices=0):
self.V = vertices
self.graph = defaultdict(list)
def read_File(self, inputfile):
vertices = 0
with open(inputfile, 'r') as graphInput:
for line in graphInput:
vertices = vertices + 1
self.V = vertices
i = 0
with open(inputfile, 'r') as graphInput:
for line in graphInput:
ints = [int(x) for x in line.split()]
j = 0
for v in ints:
if v:
self.addEdge(i, j)
j = j + 1
i = i + 1
def addEdge(self, u, v):
self.graph[u].append(v)
def DFSUtil(self, v, visited):
visited[v] = True
output = str(v) + ' '
for i in self.graph[v]:
if visited[i] == False:
ch = self.DFSUtil(i, visited)
output = output + ch
return output
def fillOrder(self, v, visited, stack):
visited[v] = True
for i in self.graph[v]:
if visited[i] == False:
self.fillOrder(i, visited, stack)
stack = stack.append(v)
def getTranspose(self):
g = SCC_Graph(self.V)
for i in self.graph:
for j in self.graph[i]:
g.addEdge(j, i)
return g
def printSCCs(self):
output = ''
stack = []
visited = [False] * (self.V)
for i in range(self.V):
if visited[i] == False:
self.fillOrder(i, visited, stack)
gr = self.getTranspose()
visited = [False] * (self.V)
while stack:
i = stack.pop()
if visited[i] == False:
ch = gr.DFSUtil(i, visited)
output = output + ch + '\n'
return output