利用Breadth-First Search (BFS)算法寻找图中的最短路径和所有路径
来源:互联网 发布:如何管理网络客服 编辑:程序博客网 时间:2024/06/15 01:51
今天在stackoverflow网站搜索问题时,发现了一个用BFS算法搜索图中最短路径比较简洁且容易理解的代码。暂且放在博客记录下来,方便今后用到。
如上图,我们要使用BFS算法搜索1—11的最短路径,代码如下:
# graph is in adjacent list representationgraph = { '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 found if node == end: return path # enumerate all adjacent nodes, construct a new path and push it into the queue for adjacent in graph.get(node, []): new_path = list(path) new_path.append(adjacent) queue.append(new_path)print bfs(graph, '1', '11')
输出结果:[1,4,7,11]
如果我们修改几个地方,增加了节点3的临节点,网络拓扑已改变。则可以得到源和目的节点的所有路径,代码如下:
# graph is in adjacent list representationgraph = { 1: [2, 3, 4], 2: [5, 6], 3: [4,11], 5: [9, 10], 4: [7, 8], 7: [11, 12] }def bfs(graph, start, end): # maintain a queue of paths queue = [] allpath = [] # 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 found if node == end: allpath.append(path) # enumerate all adjacent nodes, construct a new path and push it into the queue for adjacent in graph.get(node, []): new_path = list(path) new_path.append(adjacent) queue.append(new_path) return allpathprint bfs(graph, 1, 11)
输出结果:[[1, 3, 11], [1, 4, 7, 11], [1, 3, 4, 7, 11]]
阅读全文
0 0
- 利用Breadth-First Search (BFS)算法寻找图中的最短路径和所有路径
- 寻找最短路径BFS
- bfs寻找最短路径并且打印路径和方向
- BFS(Breadth First Search)
- 寻找最短路径
- 算法-图论-Dijstra寻找最短路径
- JS算法*START寻找最短路径
- BellMan-Ford算法--寻找最短路径
- Dijkstra算法--寻找最短路径
- bfs最短路径
- BFS 算法求解最短路径
- 迷宫的最短路径-BFS算法
- Tree-BFS(Breadth-First-Search)
- 广度优先搜索算法(Breadth-First-Search,BFS)
- 广度优先搜索算法(breadth First Search, BFS)
- BFS—— Breadth First Search 广度优先算法
- [数据结构]广度优先搜索算法(Breadth-First-Search,BFS)
- BFS——广度优先算法(Breadth First Search)
- xgboost原理
- FFMPEG结构体分析:AVIOContext
- HDU 6031 Innumerable Ancestors【LCA】
- 比较好的取色工具汇总
- activemq 添加生产者消费者连接密码
- 利用Breadth-First Search (BFS)算法寻找图中的最短路径和所有路径
- 把一个数组最开始的若干个元素搬到数组的末尾,我们称之为数组的旋转。 输入一个非递减排序的数组的一个旋转,输出旋转数组的最小元素。 例如数组{3,4,5,1,2}为{1,2,3,4,5}的一个旋转,该数
- Android异常之fragment添加ViewPager
- Android应用层制作LED指示灯
- 统计cpu相关信息
- UVA489解题报告(刽子手游戏)
- 【C#】之字符串处理
- 引入RxJava2,运行时报: Duplicated file rxjava.properties错误
- ListView嵌套ListView