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")