具有墙的二维阵列上的A * star搜索算法的优化

时间:2019-10-29 09:22:49

标签: javascript algorithm data-structures dijkstra a-star

我正在尝试实现A * star搜索算法,但是我成功实现了它,但是有时它不能产生最佳的最短路径,我想知道是否可以优化算法以产生更好的最短路径? (我的意思是最短路径实际上不是最短路径)

此刻,我正在跟踪每个邻居的父节点以找到最短路径,这就是问题所在,因此,当我将FinishNode最后添加到VisitedNodesInOrder数组时,我可以访问该父节点。让我们以最快的速度到达该单元格,然后一直返回直到到达startNode,在这种情况下父级为null。

在有墙的情况下,它无法按预期方式工作,因为它只有在到达墙后才能看到墙,因此它采用了非最佳路径,因此当我从FinishNode追溯时,它遵循非最佳路径。

这是否应该像这样工作?还是有一种方法可以让算法在尝试采用非最佳路径之前先考虑墙?

网格由节点对象的2D数组组成,该数组具有行,列和NodeType属性。

每个节点的邻居由其旁边的四个单元组成(左,右,上,下)

const aStar = (grid, startNode, finishNode) => {
    const n = grid.length;
    const m = grid[0].length;

    const endRow = finishNode.row;
    const endCol = finishNode.col;


    const visitedNodesInOrder = [];

    const pq = new PriorityQueue((a, b) => a.distance < b.distance);

    startNode.parent = null;

    //Store in an object {node: {row, col, parent}, distance: x}
    //Distance refers to distance to FinishNode

    pq.push({node: startNode, distance: Math.abs(endRow - startNode.row) + Math.abs(endCol - startNode.col)});

    while(!pq.isEmpty()){
        const {node} = pq.pop();

        const row = node.row;
        const col = node.col;
        const parent = node.parent;

        if(grid[row][col].nodeType == NodeType.VISITED_NODE){
            continue;
        }

        if (grid[row][col].nodeType === NodeType.FINISH_NODE) {
            visitedNodesInOrder.push({row, col, parent});
            break;
        }

        if (grid[row][col].nodeType === NodeType.WALL_NODE) {
            continue;
        }

        if (row < n - 1) {
            pq.push({node: {row: row + 1, col, parent: {row, col}}, distance: Math.abs(endRow - row + 1) + Math.abs(endCol - col)});
        }

        if (row > 0) {
            pq.push({node: {row: row - 1, col, parent: {row, col}}, distance: Math.abs(endRow - row - 1) + Math.abs(endCol - col)});
        }

        if (col < m - 1) {
            pq.push({node: {row: row, col: col + 1, parent: {row, col}}, distance: Math.abs(endRow - row) + Math.abs(endCol - col + 1)});
        }

        if (col > 0) {
            pq.push({node: {row: row, col: col - 1, parent: {row, col}}, distance: Math.abs(endRow - row) + Math.abs(endCol - col - 1)});
        }

        if (grid[row][col].nodeType === NodeType.EMPTY_NODE) {
            visitedNodesInOrder.push({row, col, parent: parent});
            grid[row][col].nodeType = NodeType.VISITED_NODE;
        }

    }

    return visitedNodesInOrder
};

enter image description here

图片中的蓝色表示受访节点,黑色是墙壁,黄色路径是“最短”路径。

0 个答案:

没有答案
相关问题