python实现广度优先算法

参考博客: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')
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值