我写了一个小的递归算法,用于解决以下格式迷宫问题。
在第一个块中,我找到并拆分了路径。存有路径的char[][]数组也被设置,随后作为结果打印出来。
这个方法运行良好,但是我想知道如何最好地修改它,以便不在找到第一条成功的路径后就停止,而是继续寻找最短可能的路径。
我尝试做了一些修改,在findPath()函数中添加了shortestPath和hasFoundPath变量。shortestPath表示迄今为止找到的最短路径长度,而hasFoundPath变量则表示是否已经找到任何路径。
###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[][]数组也被设置,随后作为结果打印出来。
这个方法运行良好,但是我想知道如何最好地修改它,以便不在找到第一条成功的路径后就停止,而是继续寻找最短可能的路径。
我尝试做了一些修改,在findPath()函数中添加了shortestPath和hasFoundPath变量。shortestPath表示迄今为止找到的最短路径长度,而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()方法只是在移动之前确保上/左/下/右坐标有效。所以它确保字符是'_'或'E',并且没有越界。