-
Notifications
You must be signed in to change notification settings - Fork 3
/
BFS and DFS.py
73 lines (57 loc) · 1.69 KB
/
BFS and 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
class Graph:
def __init__(self, vertices):
self.V = vertices
self.graph = {}
def add_edge(self, src, dest):
##for adjacency list
if self.graph.get(src) == None:
self.graph[src]=[dest]
else:
self.graph[src]=self.graph.get(src)+[dest]
if self.graph.get(dest) == None:
self.graph[dest]=[src]
else:
self.graph[dest]=self.graph.get(dest)+[src]
def BFS(self, s):
visited = set()
queue = []
visited.add(s)
queue.append(s)
while queue:
s = queue.pop(0)
print (s, end = " ")
for node in self.graph[s]:
if node not in visited:
visited.add(node)
queue.append(node)
def DFS(self,s):
visited = set()
stack = []
stack.append(s)
while (len(stack)):
s=stack.pop()
if s not in visited:
print(s,end=' ')
visited.add(s)
for node in self.graph[s]:
if node not in visited:
stack.append(node)
V = 6
graph = Graph(V)
graph.add_edge('R', 'M')
graph.add_edge('M', 'N')
graph.add_edge('M', 'Q')
graph.add_edge('Q', 'P')
graph.add_edge('N', 'O')
graph.add_edge('O', 'P')
graph.add_edge('N', 'Q')
print('Breath First Search: ',end='')
graph.BFS('Q')
print()
print('Depth First Search: ',end='')
graph.DFS('Q')
##OUTPUT:
'''
Breath First Search: Q M P N R O
Depth First Search: Q N O P M R
'''