BFS(Breadth-First Search)
一、BFS 的核心概念
二、節點結構設計(以樹為例)
class TreeNode:
def __init__(self, value):
self.value = value
self.children = [] # 可擴展為多叉樹結構三、BFS 搜尋實作(傳回路徑)
from collections import deque
def bfs(root_node, goal_value):
path_queue = deque()
path_queue.appendleft([root_node]) # 初始路徑包含根節點
while path_queue:
current_path = path_queue.pop()
current_node = current_path[-1]
print(f"Searching node with value: {current_node.value}")
if current_node.value == goal_value:
return current_path
for child in current_node.children:
new_path = current_path[:]
new_path.append(child)
path_queue.appendleft(new_path)
return None # 未找到則回傳 None四、完整範例:樹上的 BFS
五、BFS 特性與適用情境
特性
說明
Last updated