简体   繁体   English

使用BFS的网格中的最短路径

[英]Shortest path in a grid using BFS

The grid consists of following items as python list of lists 网格由以下项目组成,如python列表列表

g = [
    ['1', '1', '1', '1', '1'],
    ['S', '1', 'X', '1', '1'],
    ['1', '1', '1', '1', '1'],
    ['X', '1', '1', 'E', '1'],
    ['1', '1', '1', '1', 'X']
]

S indicates the start, E indicates the end. S表示开始,E表示结束。

1 indicates the allowed paths, X are not allowed paths 1表示允许的路径,X表示不允许的路径

A simple BFS traversal code is 一个简单的BFS遍历代码是

def find_path_bfs(s, e, grid):
    queue = list()
    path = list()
    queue.append(s)

    while len(queue) > 0:
        node = queue.pop(0)
        path.append(node)
        mark_visited(node, v)

        if node == e:
            break

        adj_nodes = get_neighbors(node, grid)
        for item in adj_nodes:
            if is_visited(item, v) is False:
                queue.append(item)

    return path

The algorithm, as far as I can tell is traversing correctly with the following output 据我所知,该算法使用以下输出正确遍历

[(1, 0), (1, 1), (2, 0), (0, 0), (2, 1), (0, 1), (2, 1), (0, 1), (2, 2), (3, 1), (0, 2), (2, 2), (3, 1), (0, 2), (2, 3), (3, 2), (3, 2), (4, 1), (0, 3), (2, 3), (3, 2), (3, 2), (4, 1), (0, 3), (2, 4), (3, 3)]

Each tuple in the list represents the indices for the node in the original graph. 列表中的每个元组代表原始图中节点的索引。

How can rewrite my BFS code to return the shortest path instead of the entire traversal path followed to reach the destination node? 如何重写我的BFS代码以返回最短路径,而不是返回到达目标节点的整个遍历路径? I have spent hours to find answers on my own but so far I have been unsuccessful. 我已经花费了数小时独自寻找答案,但到目前为止我一直没有成功。

In order to get shortest path you should save path to current node in your queue too, so format of queue item will be: 为了获得最短路径,您还应该将当前节点的路径也保存在队列中,因此队列项的格式为:

(node, path_to_this_node)

Modified code: 修改后的代码:

def find_path_bfs(s, e, grid):
    queue = [(s, [])]  # start point, empty path

    while len(queue) > 0:
        node, path = queue.pop(0)
        path.append(node)
        mark_visited(node, v)

        if node == e:
            return path

        adj_nodes = get_neighbors(node, grid)
        for item in adj_nodes:
            if not is_visited(item, v):
                queue.append((item, path[:]))

    return None  # no path found

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM