2

我有以下代码:

public void generateTree(Node myNode) {
    for(int i = 1; i <= 6; i++) {
        //Creating child node
        Node child = new Node();

        //Setting new Depth
        child.setDepth(myNode.getDepth()+1);

        //Adding node to tree
        myTree.add(child);

        //If the game isn't over and we're not reached the maximum depth, recurse
        if(!isGameOver() && child.getDepth() < MAX_DEPTH)
            generateTree(child);
    }
}

基本上 MAX_DEPTH 是一个整数,表示我想在游戏中探索移动树的最大深度,getDepth() 返回作为参数提交的节点的深度,setDepth 设置新节点的深度。

出于某种原因,它似乎会产生无限递归但是......有什么建议吗?

4

1 回答 1

0

你的问题不是无限递归。这可能是别的东西。这段代码对我有用 -

import java.util.ArrayList;
import java.util.List;


public class Node 
{

    private int depth;

    public static final int MAX_DEPTH = 2;

    private static List<Node> myTree = new ArrayList<Node>(); // for testing purposes

    public void generateTree(Node myNode) {
        for(int i = 1; i <= 6; i++) {
            //Creating child node
            Node child = new Node();

            //Setting new Depth
            child.setDepth(myNode.getDepth()+1);

            //Adding node to tree
            myTree.add(child);

            //If the game isn't over and we're not reached the maximum depth, recurse
            if(child.getDepth() < MAX_DEPTH)
                generateTree(child);
        }
    }

    public static void main(String [] args)
    {
        Node node = new Node();

        Node myNode = new Node();
        myNode.setDepth(0);

        node.generateTree(myNode);

        System.out.println(myTree.size());

    }

    public int getDepth() {
        return depth;
    }

    public void setDepth(int depth) {
        this.depth = depth;
    }

}

我得到的输出是

42 
于 2013-04-25T23:43:45.483 回答