-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbfs.py
88 lines (64 loc) · 1.65 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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
from queue import Queue
class TreeNode():
def __init__(self, data):
self.data = data
self.left = None
self.right = None
class GraphNode():
def __init__(self,data):
self.data = data
self.neighbors = []
def bf_traversal(root):
q = Queue()
q.enqueue(root)
path = []
while not q.isEmpty():
curr = q.dequeue()
path.append(curr.data)
if curr.left:
q.enqueue(curr.left)
if curr.right:
q.enqueue(curr.right)
return path
def bf_traversal_yield(root):
q = Queue()
q.enqueue(root)
while not q.isEmpty():
curr = q.dequeue()
yield curr.data
if curr.left:
q.enqueue(curr.left)
if curr.right:
q.enqueue(curr.right)
def bf_graph(root):
q = Queue()
seen_it = set()
path = []
q.enqueue(root)
seen_it.add(root)
while not q.isEmpty():
curr = q.dequeue()
path.append(curr.data)
for neighbor in curr.neighbors:
if neighbor not in seen_it:
q.enqueue(neighbor)
seen_it.add(neighbor)
return path
def bf_graph_adjacency(start_node_idx, adjacency_list):
q = Queue()
seen_it = set()
path = []
q.enqueue(start_node_idx)
seen_it.add(start_node_idx)
while not q.isEmpty():
curr_node = q.dequeue()
path.append(curr_node)
for node in adjacency_list[curr_node]:
if node not in seen_it:
q.enqueue(node)
seen_it.add(node)
return path
# root = SomeNode()
#
# for node in bf_traversal_yield(root):
# print(node)