-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBFS_DFS.py
79 lines (63 loc) · 1.99 KB
/
BFS_DFS.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
from collections import defaultdict
class Graph:
def __init__(self, vertices):
self.V= vertices #No. of vertices
self.graph = defaultdict(list)
def addEdge(self, u,v):
self.graph[u].append(v)
def reverse_graph(self):
reversed = Graph(self.V)
for i in self.graph:
for j in self.graph[i]:
reversed.addEdge(j,i)
return reversed
def BFS(self, s):
visited = [False]*(self.V)
queue = []
queue.append(s)
visited[s]= True
while queue:
s = queue.pop(0)
print(str(s), end='')
for i in self.graph[s]:
if visited[i] == False:
visited[i]= True
queue.append(i)
def DFS_loop(self,v, visited, stack):
visited[v] = True
print(v, end='')
for i in self.graph[v]:
if visited[i] == False:
self.DFS_loop(i, visited, stack)
def DFS(self, v, stack):
visited= [False]*(max(self.graph)+1)
self.DFS_loop(v, visited, stack)
# def fillOrder(self,v,visited, stack):
# # Mark the current node as visited
# visited[v]= True
# #Recur for all the vertices adjacent to this vertex
# for i in self.graph[v]:
# if visited[i]==False:
# self.fillOrder(i, visited, stack)
# stack = stack.append(v)
def printSCC(self):
visited = [False]*self.V
stack= []
for i in range(self.V):
if visited[i]==False:
self.fillOrder(i,visited, stack)
print('stack:', stack)
g_rev = g.reverse_graph()
while stack:
i = stack.pop()
g_rev.DFS
g = Graph(7)
g.addEdge(0,1)
g.addEdge(1,2)
g.addEdge(2,3)
g.addEdge(3,1)
g.addEdge(1,4)
g.addEdge(4,5)
g.addEdge(5,6)
g.addEdge(6,4)
g.printSCC()