【发布时间】:2016-03-22 17:22:41
【问题描述】:
我正在尝试使用递归来解决迷宫问题。在下面的代码中,MazeCoord 是一个程序员创建的类型,它存储了一个坐标类型的位置。格式为 MazeCoord(int x, int y)。我的程序现在编译时,到达方法的某些部分并忽略其他部分,因此在所有情况下都说“未找到路径”,并且只将开始位置存储在 LinkedList mazePath 中。 search() 方法中有一个注释掉的部分,这是我尝试的另一种方法,但我很确定这是错误的,而不是这样做的方法。
感谢任何帮助。
递归代码:
/** 返回穿过迷宫的路径。第一个元素是起始位置,并且 最后一个元素是退出位置。如果没有路径,或者如果这被称为 搜索前,返回空列表。
@return 迷宫路径 */
public LinkedList<MazeCoord> getPath() {
return mazePath;
}
/** 找到一条穿过迷宫的路径(如果有的话)。客户端可以访问 通过 getPath 方法找到的路径。 @return 是否找到路径。 */
public boolean search() {
currentLoc = new MazeCoord(startLoc.getRow(), startLoc.getCol());
visitedPath = new boolean[mazeData.length][mazeData[0].length];
mazePath=new LinkedList<MazeCoord>();
if(hasWallAt(startLoc) || hasWallAt(endLoc)){
return false;
}
else{
mazePath.add(currentLoc);
return appendToSearch(currentLoc.getRow(), currentLoc.getCol());
}
/**
System.out.println("try1");
mazePath.add(new MazeCoord(startLoc.getRow(), startLoc.getCol()));
boolean searchResult = appendToSearch(numRows()-1, numCols()-1);
System.out.println("test: " + searchResult);
System.out.println("test2: row, col --> " + (numRows()-1) + " , " + (numCols()-1));
System.out.println("test3: wallValue:" + hasWallAt(new MazeCoord(numRows()-1,numCols()-1)));
if(searchResult){
System.out.println("try2");
mazePath.add(new MazeCoord(numRows()-1, numCols()-1));
}
return searchResult;
*/
}
/**将执行的 search() 方法的帮助函数 实际递归获得通过迷宫的路径 @param row 当前位置所在的行 @param col 当前位置的列 @return true 如果路径可用 */
private boolean appendToSearch(int row, int col) {
//Check if within the maze
if((row - 1 < 0) || (col - 1 < 0) || (row + 1 > numRows()) || (col + 1 > numCols())){
return false;
}
//Check if the position is the exit location
if(row == endLoc.getRow() && col == endLoc.getCol()){
mazePath.add(new MazeCoord(row, col));
return false;
}
//Check for Wall
if(hasWallAt(new MazeCoord(row, col))){
return false;
}
//Check if the position has already been visited
if(visitedPath[row][col]){
return false;
}
//If all pass --> add to visitedPath
visitedPath[row][col]=true;
//Check to the Right
if(appendToSearch(row, col + 1)){
mazePath.add(new MazeCoord(row, col + 1));
return true;
}
//Check Downwards
else if(appendToSearch(row + 1, col)){
mazePath.add(new MazeCoord(row + 1, col));
return true;
}
//Check to the Left
else if(appendToSearch(row, col - 1)){
mazePath.add(new MazeCoord(row, col - 1));
return true;
}
//Check Upwards
else if(appendToSearch(row - 1, col)){
mazePath.add(new MazeCoord(row - 1, col));
return true;
}
return false;
}
【问题讨论】: