【问题标题】:Stackoverflow when performing recursion执行递归时的 Stackoverflow
【发布时间】:2012-10-01 06:52:28
【问题描述】:

我在执行此递归时收到 stackoverflow 错误。 有一种模式,它先说一次:

在 MazeGui.move(MazeGui.java:79) 这是行 if(rigting.goal == 真的){

然后它说以下两个,并且它们都在输出中重复了很长时间。问题发生在某个地方,我只是不确定是什么:

在 MazeGui.move(MazeGui.java:89) 这是线移动(rigting.right, 位置); //向右移动

在 MazeGui.move(MazeGui.java:107) 这是线移动(rigting.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 recursion stack-overflow


【解决方案1】:

您的“路径”算法有一个简单的递归循环。

在这种情况下,您的算法计算出您必须向右移动。然后,一旦你这样做了,它就会计算出你必须向左移动。一旦你向左移动,你就会回到你上次所处的位置。由于你回到了起始位置,循环重新开始,并以这种方式无限地继续(或者,真的,直到堆栈溢出)。

一个可能的解决方案是分析您的应用程序的状态,并在状态更新的任何时候检测您之前是否处于该状态;如果是,请相应地修改您的操作。

【讨论】:

    【解决方案2】:

    你可能想尝试这样的事情,

    public boolean move(Maze rigting, int pos)
    
    {
        if (rigting.goal == true)
        {
             return true;
        }
    
        if (rigting.wallR != true)
        {
             pos += 1;
             showLabel(pos);
             return move(rigting.right, pos); //moves right
        }
    
        if(rigting.wallD != true) //checks if there is a wall below
        {
            pos += 10;
            showLabel(pos);
            return move(rigting.down, pos); //moves down
        }
        if(rigting.wallL != true) //checks if there is a wall on the left
        {
            pos -= 1;
            showLabel(pos);
            return move(rigting.left, pos); //moves left
        }
    
        if(rigting.wallU != true) //checks if there is a wall above
        {
            pos -= 10;
            showLabel(pos);
            return move(rigting.up, pos); //moves up
        }
    
        return false;
    }
    

    【讨论】:

      猜你喜欢
      • 2016-07-19
      • 2011-12-26
      • 2018-01-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-07-03
      • 2013-11-15
      • 2016-03-25
      相关资源
      最近更新 更多