【发布时间】:2012-07-13 21:08:09
【问题描述】:
我正在尝试使用递归解决迷宫。它被声明为Cell [][] maze。
public class Cell {
private Wall left;
private Wall right;
private Wall up;
private Wall down;
private boolean end;
// Setters and getters not shown
}
如果单元格的某侧没有Wall,则它的值为null,否则它引用Wall 对象。 Wall 引用是一致的:与单个墙相邻的两个单元格都使用适当的字段引用它。如果缺少一堵墙,则两个相邻单元格都有对应的null 条目。这是搜索:
public boolean solveMaze(Cell[][] maze, int i, int j) {
if (maze[i][j].isEnd()){
System.out.println(maze[i][j].toString());
return true;
}
if (maze[i][j].getDown() == null) {
return solveMaze(maze, i, j + 1);
}
if (maze[i][j].getUp() == null) {
return solveMaze(maze, i, j - 1) ;
}
if (maze[i][j].getLeft() == null) {
return solveMaze(maze, i - 1, j);
}
if (maze[i][j].getRight() == null) {
return solveMaze(maze, i + 1, j) ;
}
return false;
}
我收到 Stack Overflow 错误。我的递归停止条件有什么问题?
更新:
在您高度赞赏的帮助下,我解决了这个问题:这是完美无缺的正确解决方案:
public boolean solveMaze(Cell[][] maze, int i, int j){
if (maze[i][j].isEnd()){
System.out.println("Maze Exit :["+i+","+j+"]" );
return true;
}
if (maze[i][j].isVisited()){
return false;
}
maze[i][j].setVisited(true);
if ((maze[i][j].getButtom() == null) ){
if (solveMaze(maze,i,j+1)==true)
return true;
}
if ((maze[i][j].getUp() == null) ){
if ( solveMaze(maze,i,j-1) ==true )
return true;
}
if ((maze[i][j].getLeft() == null)){
if (solveMaze(maze,i-1,j))
return true;
}
if ((maze[i][j].getRight() == null)){
if (solveMaze(maze,i+1,j))
return true;
}
maze[i][j].setVisited(false);
return false;
}
未来可能会对任何机构有所帮助。
【问题讨论】:
-
“getButton()”应该是“getBottom()”吗?
-
@millimoose 这显然是一个面试问题。那些怎么能得到应聘的呢?
-
@millimoose,我不明白你为什么称它为作业,我给出的解决方案不起作用,我需要帮助。对不起,你的评论发错地方了!!!
-
@user992484,这不是面试题,我把它标记为面试题,因为这样的问题在面试中经常被问到。无论如何,我删除了那个标签。
-
;) 不是问题。好问题,期待答案