1. 程式人生 > >python實現廣度優先搜尋

python實現廣度優先搜尋

思路:用字典來實現圖,key值為節點,每個key對應的value值為一個佇列,儲存該節點的所有鄰居節點。

# 廣度優先搜尋from collections import deque defresearch():# 字典模擬圖結構,假設從“you”出發,朋友關係網裡找賣家,沒有就在朋友的朋友的關係網裡找。。。    graph =dict()    graph["you"] = ["alice", "bob", "claire"]    graph["bob"] = ["anuj", "peggy"]    graph["alice"] = ["peggy"]    graph["claire"]
= ["thom", "jonny"]    graph["anuj"] = []    graph["peggy"] = []    graph["thom"] = []    graph["jonny"] = []# 建立一個佇列,將首節點的鄰居加入搜尋隊列    que = deque()    que += graph["you"]# 用於標記是否被檢查    researched = []while que:# 佇列不為空,取出第一個人        person = que.popleft()if person notin researched:if person_is_seller(person):
print(person +" is a seller")returnTrueelse:# 當前搜尋的人不是賣家,新增進已檢查佇列                researched.append(person)                que += graph[person]returnFalse defperson_is_seller(name):# 假設名字最後一個字母為m的人就是賣家return name[-1] =="m"