今天在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