假设名字name[-1] == ‘m’,为经销商,怎样通过你(’you‘)找到thom,并且不出现重复
search('you')from queue 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] #将当前名字也就是 'you',加入队列
searched = [] #用于记录检查过的人
while search_queue: # 如果队列中有值
person = search_queue.popleft() # 获取最左边的第一个元素,抽取一个人出来
if person not in searched: #并且不是已经查过的人
if person_is_seller(person):# 查看是否为真
print('就是他',person)
return True
else: #
search_queue += graph[person] # 如果这个人不是销售商,将这个人的所有朋友加入到搜索队伍中
searched.append(person) #将标记为检查过
return False
search('you')
运行时间
如果在整个人际关系网中,搜索芒果经销商,就意味着沿着每一条边前行,
(边是从一个人到另一个人的箭头或链接),因此运行时间至少为O(边数)。
使用了一个队列,其中包含了,要检查的每个人,将一个人添加到队列时间是O(1),
因此每个人都要这样做,所以广度优先搜索的运行时间为O(人数+边数),通常写作O(V+E),
其中V为顶点数,E为边数。