Python-廣度優先搜索

如圖所示:app

 

以此圖爲例尋找末尾爲「m」的名稱。這裏使用廣度優先搜索,這個能夠回答兩類問題:函數

第一類問題:從節點A出發,有前往節點B的路徑嗎?code

第二類問題:從節點A出發,前往節點B的哪條路徑最短?blog

那這裏其實就是尋找末尾爲「m」名稱的最短路徑。隊列

from collections import deque


def person_is_seller(name):
return name[-1] == 'm'

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 search(name):
search_queue = deque()
search_queue += graph[name]
searched = []
while search_queue:
person = search_queue.popleft()
if person not in searched:
if person_is_seller(person):
print(person + ' is a mongo seller')
return True
else:
search_queue += graph[person]
searched.append(person)
return False

search("you")

這裏使用到了散列表的概念,以及Python中deque函數來建立一個雙端隊列。 io

相關文章
相關標籤/搜索