python實現廣度有限搜尋

2021-10-04 07:15:23 字數 1343 閱讀 3696

from collections import deque

from collections import namedtuple

def bfs(start_node, end_node, graph):

node = namedtuple('node', 'name, from_node')

search_stack = deque() # 這裡當作棧使用

name_search = deque()

visited = {}

path =

path_len = 0

print('開始搜尋...')

while search_stack:

print('待遍歷節點: ', name_search)

current_node = search_stack.pop() # 使用棧模式,即後進先出,這是dfs的核心

name_search.pop()

if current_node.name not in visited:

print('當前節點: ', current_node.name, end=' | ')

if current_node.name == end_node:

pre_node = current_node

while true:

if pre_node.name == start_node:

break

else:

pre_node = visited[pre_node.from_node]

path_len = len(path) - 1

break

else:

visited[current_node.name] = current_node

for node_name in graph[current_node.name]:

if node_name not in name_search:

print('搜尋完畢,路徑為:', path[::-1], "長度為:", path_len) # 這裡不再是最短路徑,深度優先搜尋無法一次給出最短路徑

if __name__ == "__main__":

graph = dict()

graph[1] = [3, 2]

graph[2] = [5]

graph[3] = [4, 7]

graph[4] = [6]

graph[5] = [6]

graph[6] = [8]

graph[7] = [8]

graph[8] =

bfs(1, 8, graph)

python實現廣度有限搜尋

from collections import deque from collections import namedtuple def bfs start node,end node,graph 開始節點 目標節點 圖字典 node namedtuple node name,from node 使...

廣度優先搜尋(BFS) Python實現

演算法的工作原理 建立乙個佇列,用於儲存要檢查的人 從佇列中彈出乙個人 檢查這個人是否被檢查過 檢查這個人是否為芒果經銷商 是 大功告成 否 將這個人的所有鄰居都加入到佇列中 回到第二步 如果隊列為空,就說明沒有找到芒果經銷商 encoding utf 8 from collections impo...

python實現廣度優先搜尋,查詢芒果經銷商

from collections import deque graph 建立乙個字典,儲存人際關係圖 graph you alice bob claire graph bob anuj peggy graph alice peggy graph claire thom jonny graph anu...