Why is my recursion keep throwing a StackOverflow error?

五迷三道 提交于 2020-01-17 05:21:25

问题


I am trying to generate a tree, of all the possible states of the 8-N problem, with no duplicates. 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;
    }

回答1:


Your state is too big to fit the stack. Test your algorithm:

  • with a smaller sample.
  • or increase your stack size (e.g. java -Xss4m)



回答2:


You should edit 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;
}


来源:https://stackoverflow.com/questions/37810488/why-is-my-recursion-keep-throwing-a-stackoverflow-error

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!