执行此递归时,我收到堆栈溢出错误。 有一个模式,它第一次说:
at MazeGui.move(MazeGui.java:79) which is line if(rigting.goal == true) {
然后它会显示以下两个内容,并且这两个内容在输出中重复了很长一段时间。问题发生在某个地方,我只是不确定是什么:
at MazeGui.move(MazeGui.java:89) which is line move(rigting.right, pos); //moves right
at MazeGui.move(MazeGui.java:107) which is line move(rigting.left, pos); //moves left
...
...
我是否缺少终止条件或其他什么,是否发生了无限递归?我无法理解它,完全迷失了。任何帮助将不胜感激。
代码:
public boolean move(Maze rigting, int pos)
{
if (rigting.goal == true)
{
return true;
}
if (rigting.wallR != true)
{
pos += 1;
move(rigting.right, pos); //moves right
showLabel(pos);
return true;
}
if(rigting.wallD != true) //checks if there is a wall below
{
pos += 10;
move(rigting.down, pos); //moves down
showLabel(pos);
return true;
}
if(rigting.wallL != true) //checks if there is a wall on the left
{
pos -= 1;
move(rigting.left, pos); //moves left
showLabel(pos);
return true;
}
if(rigting.wallU != true) //checks if there is a wall above
{
pos -= 10;
move(rigting.up, pos); //moves up
showLabel(pos);
return true;
}
return false;
}
最佳答案
您的“路径”算法有一个简单的递归循环。
在这种情况下,您的算法计算出您必须向右移动。一旦你这样做了,它就会计算出你必须向左移动。一旦你向左移动,你就回到了上次所在的位置。由于你回到了起始位置,循环重新开始并以这种方式无限地继续(或者,实际上,直到出现堆栈溢出)。
一个可能的解决方案是分析应用程序的状态,并在状态更新时检测您之前是否处于该状态;如果是,请相应地修改您的行为。
关于java - 执行递归时出现 Stackoverflow,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12665772/