-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBFS.py
More file actions
35 lines (31 loc) · 860 Bytes
/
BFS.py
File metadata and controls
35 lines (31 loc) · 860 Bytes
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
from collections import defaultdict
class Graph:
def __init__(self):
self.graph = defaultdict(list)
def addEdge(self,u,v):
self.graph[u].append(v)
def BFS(self, s):
visited = [False] * (len(self.graph))
queue = []
queue.append(s)
visited[s] = True
while queue:
s = queue.pop(0)
print (s, end = " ")
for i in self.graph[s]:
if visited[i] == False:
queue.append(i)
visited[i] = True
q=int(input('enter no. of edges'))
print()
g = Graph()
for i in range(q):
a,b=input("enter edge(u,v)").split()
print()
a=int(a)
b=int(b)
g.addEdge(a, b)
w=int(input("enter source vertex"))
print()
print ("Following is Bfs")
g.BFS(w)