用递归算法求迷宫中的最短路径

时间:2015-05-30 20:41:59

标签: java algorithm recursion maze

我制作了一个小递归算法,以下列格式找到迷宫的解决方案

###S###
##___##
##_#_##
#__#_##
#E___##

其中'#'代表墙,'_'代表开放空间(可自由移动)。 'S'代表起始位置,'E'代表结束位置。

我的算法工作正常,但我想知道如何修改它以适应最短的路径。

/**
 * findPath()
 * 
 * @param location - Point to search
 * @return true when maze solution is found, false otherwise
 */
private boolean findPath(Point location) {
    // We have reached the end point, and solved the maze
    if (location.equals(maze.getEndCoords())) {
        System.out.println("Found path length: " + pathLength);
        maze.setMazeArray(mazeArray);
        return true;
    }

    ArrayList<Point> possibleMoves = new ArrayList<Point>();
    // Move Right
    possibleMoves.add(new Point(location.x + 1, location.y));
    // Down Move
    possibleMoves.add(new Point(location.x, location.y - 1));
    // Move Left
    possibleMoves.add(new Point(location.x - 1, location.y));
    // Move Up
    possibleMoves.add(new Point(location.x, location.y + 1));

    for (Point potentialMove : possibleMoves) {
        if (spaceIsFree(potentialMove)) {
            // Move to the free space
            mazeArray[potentialMove.x][potentialMove.y] = currentPathChar;
            // Increment path characters as alphabet
            if (currentPathChar == 'z')
                currentPathChar = 'a';
            else
                currentPathChar++;
            // Increment path length
            pathLength++;

            // Find the next path to traverse
            if (findPath(potentialMove)) {
                return true;
            }

            // Backtrack, this route doesn't lead to the end
            mazeArray[potentialMove.x][potentialMove.y] = Maze.SPACE_CHAR;
            if (currentPathChar == 'a')
                currentPathChar = 'z';
            else
                currentPathChar--;
            // Decrease path length
            pathLength--;
        }
    }

    // Previous space needs to make another move
    // We will also return false if the maze cannot be solved.
    return false;
}

在第一个区块中,我找到路径并将其分解。写入路径的char [] []数组也会被设置,稍后会打印出来作为结果。

它运作良好,但我想知道在找到第一条成功路径之后修改它以便不突破的最佳方法是什么,但一直走到它找到最短的路径。

我尝试过这样的事情,修改find​​Path()方法并添加shortestPath和hasFoundPath变量。第一个指示到目前为止找到的最短路径的长度,以及指示我们是否找到任何路径的hasFoundPath变量。

    // We have reached the end point, and solved the maze
    if (location.equals(maze.getEndCoords())) {
        System.out.println("Found path length: " + pathLength);
        // Is this path shorter than the previous?
        if (hasFoundPath && pathLength < shortestPathLength) {
            maze.setMazeArray(mazeArray);
            shortestPathLength = pathLength;
        } else if (!hasFoundPath) {
            hasFoundPath = true;
            maze.setMazeArray(mazeArray);
            shortestPathLength = pathLength;            
        }
        //return true;
    }

但是我无法让它将mazeArray设置为它可能找到的任何最短路径的正确值。

任何指导都将不胜感激:)谢谢

spaceIsFree()方法只需确保向上/向左/向下/向右坐标有效,然后再移动它们。因此,它确保char是'_'或'E',并且它不会超出范围。

2 个答案:

答案 0 :(得分:8)

您的代码似乎执行depth-first search(DFS)。要找到最短路径,您需要切换到breadth-first search(BFS)。通过在现有代码中添加一些变量,您无法做到这一点。它需要重写你的算法。

将DFS转换为BFS的一种方法是摆脱递归并切换到使用显式的堆栈来跟踪到目前为止您访问过的节点。在搜索循环的每次迭代中,您(1)从堆栈中弹出一个节点; (2)检查该节点是否是解决方案; (3)将每个孩子推到堆叠上。在伪代码中,它看起来像:

深度优先搜索

stack.push(startNode)

while not stack.isEmpty:
    node = stack.pop()

    if node is solution:
        return
    else:
        stack.pushAll(node.children)

如果您将堆栈切换到队列,这将隐式变为BFS,BFS自然会找到最短路径。

广度优先分析

queue.add(startNode)

while not queue.isEmpty:
    node = queue.remove()

    if node is solution:
        return
    else:
        queue.addAll(node.children)

补充说明:

  1. 以上算法适用于树木:没有环路的迷宫。如果您的迷宫有循环,那么您需要确保不要重新访问您已经看过的节点。在这种情况下,您需要添加逻辑来跟踪所有已访问过的节点,并避免第二次将它们添加到堆栈/队列中。

  2. 如上所述,这些算法将找到目标节点,但他们不记得在那里获得它们的路径。添加它是读者的练习。

答案 1 :(得分:0)

这是我提出的BFS搜索解决方案。 它将起点标记为“1”,然后将每个相邻的标记标记为“2”,将每个相邻的标记标记为“3”,依此类推。

然后它从结束开始,然后使用递减的“级别”值向后移动,这将导致最短的路径。

private LinkedList<Point> findShortestPath(Point startLocation) {
    // This double array keeps track of the "level" of each node.
    // The level increments, starting at the startLocation to represent the path
    int[][] levelArray = new int[mazeArray.length][mazeArray[0].length];

    // Assign every free space as 0, every wall as -1
    for (int i=0; i < mazeArray.length; i++)
        for (int j=0; j< mazeArray[0].length; j++) {
            if (mazeArray[i][j] == Maze.SPACE_CHAR || mazeArray[i][j] == Maze.END_CHAR)
                levelArray[i][j] = 0;
            else
                levelArray[i][j] = -1;
        }

    // Keep track of the traversal in a queue
    LinkedList<Point> queue = new LinkedList<Point>();
    queue.add(startLocation);

    // Mark starting point as 1
    levelArray[startLocation.x][startLocation.y] = 1;

    // Mark every adjacent open node with a numerical level value
    while (!queue.isEmpty()) {
        Point point = queue.poll();
        // Reached the end
        if (point.equals(maze.getEndCoords()))
            break;

        int level = levelArray[point.x][point.y];
        ArrayList<Point> possibleMoves = new ArrayList<Point>();
        // Move Up
        possibleMoves.add(new Point(point.x, point.y + 1));
        // Move Left
        possibleMoves.add(new Point(point.x - 1, point.y));
        // Down Move
        possibleMoves.add(new Point(point.x, point.y - 1));
        // Move Right
        possibleMoves.add(new Point(point.x + 1, point.y));

        for (Point potentialMove: possibleMoves) {
            if (spaceIsValid(potentialMove)) {
                // Able to move here if it is labeled as 0
                if (levelArray[potentialMove.x][potentialMove.y] == 0) {
                    queue.add(potentialMove);
                    // Set this adjacent node as level + 1
                    levelArray[potentialMove.x][potentialMove.y] = level + 1;
                }
            }
        }
    }
    // Couldn't find solution
    if (levelArray[maze.getEndCoords().x][maze.getEndCoords().y] == 0)
        return null;

    LinkedList<Point> shortestPath = new LinkedList<Point>();
    Point pointToAdd = maze.getEndCoords();

    while (!pointToAdd.equals(startLocation)) {
        shortestPath.push(pointToAdd);
        int level = levelArray[pointToAdd.x][pointToAdd.y];
        ArrayList<Point> possibleMoves = new ArrayList<Point>();
        // Move Right
        possibleMoves.add(new Point(pointToAdd.x + 1, pointToAdd.y));
        // Down Move
        possibleMoves.add(new Point(pointToAdd.x, pointToAdd.y - 1));
        // Move Left
        possibleMoves.add(new Point(pointToAdd.x - 1, pointToAdd.y));
        // Move Up
        possibleMoves.add(new Point(pointToAdd.x, pointToAdd.y + 1));

        for (Point potentialMove: possibleMoves)  {
            if (spaceIsValid(potentialMove)) {
                // The shortest level will always be level - 1, from this current node.
                // Longer paths will have higher levels.
                if (levelArray[potentialMove.x][potentialMove.y] == level - 1) {
                    pointToAdd = potentialMove;
                    break;
                }
            }
        }
    }

    return shortestPath;
}

spaceIsValid()只是确保空间不受限制。