mercredi 15 juin 2016

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. 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;
    }

Aucun commentaire:

Enregistrer un commentaire