forked from prosoftwaredevelopment/CompetetiveCodingPython
-
Notifications
You must be signed in to change notification settings - Fork 0
/
bfs.py.py
47 lines (43 loc) · 855 Bytes
/
bfs.py.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
from collections import deque
from collections import defaultdict
'''
V E
FOR EVERY EDGE
U V
7 9
A B
A C
A F
C E
C F
C D
D E
D G
G F
'''
# T.C = O(V+)
# S.C = O(V)
def bfs(graph,start,visited,path):
queue = deque()
path.append(start)
queue.append(start)
visited[start] = True
while len(queue) != 0:
tmpnode = queue.popleft()
for neighbour in graph[tmpnode]:
if visited[neighbour] == False:
path.append(neighbour)
queue.append(neighbour)
visited[neighbour] = True
return path
graph = defaultdict(list)
v,e = map(int,input().split())
for i in range(e):
u,v = map(str,input().split())
graph[u].append(v)
graph[v].append(u)
start = 'A'
path = []
visited = defaultdict(bool)
traversedpath = bfs(graph,start,visited,path)
print(traversedpath)