简体   繁体   English

为什么我的递归不断抛出StackOverflow错误?

[英]Why is my recursion keep throwing a StackOverflow error?

I am trying to generate a tree, of all the possible states of the 8-N problem , with no duplicates. 我正在尝试生成一个没有重复的,包含8-N 问题的所有可能状态的树。 I can do it on paper but in code I can't. 我可以在纸上做,但不能用代码做。

Here is my recursive function: 这是我的递归函数:

......
...
..
        root = new TreeNode(startingState);
        visitedStates.add(root.getData().getStateValues());

        generateStateSpaceRecursive(root);
    }

public void generateStateSpaceRecursive(TreeNode node){

    List<TreeNode> nextStatesNodes = getNextStates(node);

    for (TreeNode childNode : nextStatesNodes){
        if(!stateVisited(childNode.getData().getStateValues())) {
            visitedStates.add(childNode.getData().getStateValues());
            node.addChild(childNode);
            generateStateSpaceRecursive(childNode);
        }
    }
}

Why would it not stop? 为什么不停止?

Also if I understood the problem correctly it says, 同样,如果我正确理解了问题,它会说:

Implement the following types of search to (try to) solve this problem: depth first, breadth first, iterative deepening, some form of heuristic search. 实施以下类型的搜索以(尝试)解决此问题:深度优先,宽度优先,迭代加深,某种形式的启发式搜索。

But I need the state space first right? 但是我首先需要状态空间吗? Or I can just apply the algorithms and generate the states on the fly? 或者我可以仅应用算法并即时生成状态?

Edit: 编辑:

private List<TreeNode> getNextStates(TreeNode node) {

        List<TreeNode> nextStates = new ArrayList<>();

        if(agent.canMoveLeft(node)){
            nextStates.add(agent.moveLeft(node));
        }
        if(agent.canMoveRight(node)){
            nextStates.add(agent.moveRight(node));
        }
        if(agent.canMoveUp(node)){
            nextStates.add(agent.moveUp(node));
        }
        if(agent.canMoveDown(node)){
            nextStates.add(agent.moveDown(node));
        }

        return nextStates;
    }

Your state is too big to fit the stack. 您的状态太大,无法容纳堆栈。 Test your algorithm: 测试算法:

  • with a smaller sample. 样本较小。
  • or increase your stack size (eg java -Xss4m) 或增加堆栈大小(例如java -Xss4m)

You should edit generateStateSpaceRecursive: 您应该编辑generateStateSpaceRecursive:

public void generateStateSpaceRecursive(TreeNode node)
{    
 if(!testGoal)
  {
    //Goal node is not seen
    List<TreeNode> nextStatesNodes = getNextStates(node);    
    ...
  }
 else 
   //Goal Node Visited    
}

Create new function like this: 创建这样的新功能:

private bool testGoal(TreeNode node)
{
  if(node == goalNode) return true;
  else return false;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM