参考博客:https://blog.csdn.net/Neo233/article/details/80471794
这篇博客的代码都是基于参考博客里的题目和代码的。
BFS在这个题目中的实现思想:
1.用一个队列q存储待检查的邻居们
2.创建一个空数组t用于存储已被检查过的邻居们
3.从这个队列中弹出队列头,我们这里暂时称为邻居A,检查这位邻居A是否是芒果销售商,并把A加入到t中
4.如果是,那么你找到一个芒果销售商了
5.如果不是,把A的所有邻居加入到队列尾部,然后回到第3步
6.如果队列为空后你还是没有找到任何一个芒果销售商,那说明你的芒果卖不出去liao
代码实现如下:
#参考博客:https://blog.csdn.net/Neo233/article/details/80471794
from collections import deque
graph = {}
graph['you'] = ['alice', 'bob', 'claire']
graph['claire'] = ['jonny', 'thom']
graph['alice'] = ['peggy']
graph['bob'] = ['anuj', 'peggy']
graph['anuj'] = []
graph['thom'] = []
graph['jonny'] = []
graph['peggy'] = []
retailer = ['peggy', 'bob']
q = deque()
q += graph['you']
checked = []
flag = False
#检查该邻居是否为芒果销售商,如果是返回真,如果不是返回假
def check_person(item):
if item in retailer:
return True
return False
while q :
item = q.popleft()
if item not in checked :
if check_person(item):
print('you find the seller:', item)
flag = True
else:
q += graph[item]
checked.append(item)
if flag is not True:
print('oh no,your mango cannot sell out')