forked from ls1248659692/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbfs.py
More file actions
94 lines (79 loc) · 2.56 KB
/
Copy pathbfs.py
File metadata and controls
94 lines (79 loc) · 2.56 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
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
89
90
91
92
93
94
# Breadth-first search is traversing or searching tree or graph data structures, including graph-like solution space.
# it explores all of the neighbor nodes at the present depth prior to moving on to the nodes at the next depth level.
#
# Time: O(V+E) V: vertex, E: edges
# Space: O(V)
from collections import deque
# iteration version, using deque
def bfs_iteratively_by_queue(self, start, target=None):
queue, visited = deque([start]), {start}
while queue:
node = queue.popleft()
visited.add(node)
'''
process current node logic here
'''
self.process_logic(node)
# target is optional
if node == target:
'''
reach the goal and break out
'''
self.process_target_logic(target)
break
for next_node in node.get_successors():
if next_node not in visited:
queue.append(next_node)
# iteration version, using list, pythonic-style
# conciser but more memory, mainly used when you want to collect the whole list
def bfs_iteratively_by_list(self, start, target=None):
node_list, visited = [start], {start}
# append while traversing
for node in node_list:
visited.add(node)
'''
process current node logic here
'''
self.process_logic(node)
# target is optional
if node == target:
'''
reach the goal and break out
'''
self.process_target_logic(target)
break
for next_node in node.get_successors():
if next_node not in visited:
node_list += node
# basically the node_list is useful here
return node_list
# recursion version, uncommon
def bfs_recursively(self, queue: deque, visited: set, target=None):
if not queue:
return
node = queue.popleft()
visited.add(node)
'''
process current node logic here
'''
self.process_logic(node)
# target is optional
if node == target:
'''
reach the goal and break out
'''
self.process_target_logic(target)
return
for next_node in node.get_successors():
if next_node not in visited:
queue.append(next_node)
self.bfs_recursively(queue, visited)
# bfs list comprehension in row of binary tree
def bfs_row(self, root):
row = [root]
while row:
'''
process current node logic here
'''
# process logic separately
row = [child for node in row for child in (node.left, node.right) if node]