利用Breadth-First Search (BFS)算法寻找图中的最短路径和所有路径

本文介绍了如何使用Breadth-First Search (BFS)算法寻找图中的最短路径,并提供了修改后的代码来获取所有可能的路径。当网络拓扑变化时,BFS能有效地找出不同路径。此外,还提到了Python的networkx库,它包含多种路径算法,可以更高效地解决复杂网络中的路径问题。
摘要由CSDN通过智能技术生成

       今天在stackoverflow网站搜索问题时,发现了一个用BFS算法搜索图中最短路径比较简洁且容易理解的代码。暂且放在博客记录下来,方便今后用到。

      如上图,我们要使用BFS算法搜索1—11的最短路径,代码如下:

 

# graph is in adjacent list representation
graph = {
        '1': ['2', '3', '4'],
        '2': ['5', '6'],
        '5': ['9', '10'],
        '4': ['7', '8'],
        '7': ['11', '12']
        }

def bfs(graph, start, end):
    # maintain a queue of paths
    queue = []
    # push the first path into the queue
    queue.append([start])
    while queue:
        # get the first path from the queue
        path = queue.pop(0)
        # get the last node from the path
        node = path[-1]
        # path fou
  • 2
    点赞
  • 19
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值