广度优先搜索主要解决两类问题:
(1)从A节点出发,有到B节点的路径么?
(2)从A节点出发,到B节点的最短路径是什么?
算法复杂度为O(V+E),其中V为顶点,E为边数。
例:
假设你要在朋友中找一个芒果销售商,如果朋友中没有,则找朋友的朋友,即人际关系网。实现的是第一类问题,在你的人际关系王忠,能找到芒果销售商么?
from collections import deque # 引入队列
graph = {} # 创建人际关系网
graph['you'] = ['Alice', 'Bob', 'Claire']
graph['Alice'] = ['peggy']
graph['Bob'] = ['anuj','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