-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbfs.py
49 lines (39 loc) · 750 Bytes
/
bfs.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
from collections import deque
graph = {
'A': ['B', 'D'],
'B': ['A', 'C'],
'C': ['B'],
'D': ['A', 'E', 'F'],
'E': ['D', 'F', 'G'],
'F': ['D', 'E', 'H'],
'G': ['E', 'H'],
'H': ['G', 'F']
}
v = set()
q = deque()
p = {}
d = {}
for j in graph.keys():
d[j] = 0
p[j] = None
def bfs(start):
v.add(start)
q.appendleft(start)
while q:
m = q.pop()
print(m, end=" ")
for i in graph[m]:
if i not in v:
v.add(i)
q.appendleft(i)
p[i] = m
d[i] = d[m] + 1
bfs('A') # A B D C E F G H
print()
path = []
goal = 'G'
while goal:
path.append(goal)
goal = p[goal]
path.reverse()
print(*path) # A D E G