-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBFS.py
More file actions
26 lines (24 loc) · 700 Bytes
/
Copy pathBFS.py
File metadata and controls
26 lines (24 loc) · 700 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
from collections import deque
def BFS(graph, root):
searchQueue = deque([root])
visited = set([root])
travOrder = []
while searchQueue:
currNode = searchQueue.popleft()
travOrder.append(currNode)
for neighbor in graph[currNode]:
if neighbor not in visited:
visited.add(neighbor)
searchQueue.append(neighbor)
return travOrder
graph = {}
graph['v'] = ['r']
graph['r'] = ['v', 's']
graph['s'] = ['w', 'r']
graph['w'] = ['t', 'x', 's']
graph['t'] = ['u', 'x', 'w']
graph['x'] = ['w', 'y', 't']
graph['y'] = ['u', 'x']
graph['u'] = ['t', 'y']
trav = BFS(graph, 's')
print(f"This is the order of traversal: {trav}")