本文章根据《算法图解》提供来写的。
# -*- coding = utf-8 -*-
# @Time : 2021/12/14 17:20
# @Author : 宁洪康
# @File : 广度优先搜索.py
# @Software : PyCharm
"""
以下是为找到芒果经销商而设计的算法
散列表graph用于映射人物关系
函数 person_is_seller 用于判断是否为芒果经销商
"""
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 person_is_seller(name):
return name[-1] == "m"
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 mango seller!")
return True
else:
search_queue += graph[person] # 弹出的不是芒果经销商,将此人朋友都加入到搜索队列
searched.append(person)
return False # 关系网中没有芒果经销商
search("you")
"""
总结:
因为要在你的整个关系网中寻找芒果经销商,因此需要沿着每条边(一个人到另一个的连线)前行,因此运行时间至少为O(边数)
还使用了队列,将每个人添加到队列的时间为O(人数)
所以广度优先搜索的运行时间为O(人数+边数),记为O(V+E)
"""