-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbfs.py
More file actions
56 lines (33 loc) · 1.07 KB
/
bfs.py
File metadata and controls
56 lines (33 loc) · 1.07 KB
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
from collections import *
from load_graph import *
def bfs(start, goal): # Defines Breadth-First Search function.
backpointers = {}
d = deque()
# Add the starting Vertex to the queue.
d.append(start)
backpointers[start] = None
visited = []
# While the queue is not empty, queue and de-queue.
while len(d) != 0:
x = d.popleft()
# While not at the end of the path, adjust queue.
if x != goal:
for y in x.adjacent:
if y not in backpointers:
backpointers[y] = x
d.append(y)
# Traverse through backpointers to return list of visited Vertices.
else:
while backpointers[x] is not None:
visited.append(x)
x = backpointers[x]
visited.append(start)
return visited
# Driver code to test bfs function with graph defined in vertices.txt.
dict = load_graph("vertices.txt")
list = bfs(dict["B"], dict["G"])
set = []
for entry in list:
set.append(str(entry))
set.reverse()
print(set)