BFS 广度优先搜索 Python

BFS 广度优先搜索 Python,第1张

BFS 广度优先搜索 Python


假设a点为起始点

结果为: A   BC   DE   F

graph={ "a":["b","c"],
        "b":["a","c","d"],
        "c":["a","b","d","e"],
        "d":["b","c","e","f"],
        "e":["c","d"],
        "f":["d"]}
def bfs(graph,s):
    flag=[]
    flag.append(s)
    memory=[]
    memory.append(s)
    while(len(flag)>0):
        a=flag.pop(0)
        b=graph[a]
        for i in b:
            if i not in memory:
                flag.append(i)
                memory.append(i)
        print(a)
bfs(graph,"a")

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/zaji/5721172.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-18
下一篇 2022-12-18

发表评论

登录后才能评论

评论列表(0条)

保存