今天在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 found
if node == end:
return path
# enumerate all adjacent nodes, construct a new path and push it into the queue
new_path = list(path)
queue.append(new_path)

print bfs(graph, '1', '11')``````

如果我们修改几个地方，增加了节点3的临节点，网络拓扑已改变。则可以得到源和目的节点的所有路径，代码如下：

``````# graph is in adjacent list representation
graph = {
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
new_path = list(path)
queue.append(new_path)
return allpath

print bfs(graph, 1, 11)``````

原文作者：BFS
原文地址: https://blog.csdn.net/brightzelool/article/details/73730152
本文转自网络文章，转载此文章仅为分享知识，如有侵权，请联系博主进行删除。