-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbfs.py
60 lines (53 loc) · 1.15 KB
/
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
50
51
52
53
54
55
56
57
58
59
60
from queue import Queue
''' - D-A-B-C
/ /
H-F-E-
\ /
G
'''
adj_list = {
"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"]
}
visited = {}
level = {} #distance dict
parent = {}
bfs_traversal_output = []
queue = Queue()
for node in adj_list.keys():
visited[node] = False
parent[node] = None
level[node] = -1 #inf
print(visited)
print("=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-==--=-=-=-=-=-=-=-=-=-=-=")
print(level)
print("=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-==--=-=-=-=-=-=-=-=-=-=-=")
print(parent)
print("=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-==--=-=-=-=-=-=-=-=-=-=-=")
s = "A"
visited[s] = True
level[s] = 0
queue.put(s)
while not queue.empty():
u = queue.get() #pop first element of queue
bfs_traversal_output.append(u)
for v in adj_list[u]:
if not visited[v]:
visited[v] = True
parent[v] = u
level[v] = level[u] + 1
queue.put(v)
print(bfs_traversal_output)
v = "G"
path = []
while v is not None:
path.append(v)
v = parent[v]
path.reverse()
print(path)