-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbfs.py
More file actions
26 lines (21 loc) · 674 Bytes
/
bfs.py
File metadata and controls
26 lines (21 loc) · 674 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
#!/usr/local/bin/python3.4
from pprint import pprint as pp
graph = {'A': set('BC'),
'B': set('ADE'),
'C': set('AF'),
'D': set('B'),
'E': set('BF'),
'F': set('CE')}
def bfs(graph, start='A'):
visited, queue = set(), [start] # start = ['A']
while queue:
# print ("queue = " + str(queue))
# print ("visited = " + str(visited))
vertex = queue.pop(0) # vertex = 'A' remove first item in list
if vertex not in visited:
visited.add(vertex) # visited = ['A']
queue.extend(graph[vertex] - visited) # append ['B', 'C'] - ['A'] to queue
return visited
pp(graph)
print()
print ("bfs(graph) = " + str(bfs(graph)))