python實現廣度優先搜索


from collections import deque

#解決從你的人際關系網中找到芒果銷售商的問題
#使用字典表示映射關系
graph = {}
graph["you"] = ["alice", "bob", "claire"]
graph["bob"] = ["anuj", "peggy"]
graph["alice"] = ["peggy"]
graph["claire"] = ["thom", "jonny"]
graph["anuj"] = []
graph["peggy"] = []
graph["thom"] = []
graph["jonny"] = []

#判斷是否是要查找的目標
def is_target_node(name):
return name[-1] == 'm'

#實現廣度優先搜索算法
def search(name):
search_queue = deque() #創建一個隊列
search_queue += graph[name]
searched = [] #記錄用於檢查過的人
while search_queue: #只要隊列不為空
person = search_queue.popleft() #就取出其中的第一個人
if not person in searched: #這個人沒有被檢查過
if is_target_node(person): #判斷這個人是否是要查找的銷售商
print(person + " is target node!")
return True
else:
search_queue += graph[person] #如果這個人不是,就將這個人的朋友壓入隊列
searched.append(person) #將這個人追加到已檢查過的字典中
return False

#調用方法
search("you")


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM