2013-04-25 109 views
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设置新节点的深度。

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

+0

您是否尝试过使用print语句来获得深度的价值?或者使用调试器?如果每个子层的深度没有增加1,那么这将解释无限递归。 – Patashu 2013-04-25 23:38:45

+0

什么是MAX_DEPTH?定义无限递归 - 它只是一直持续下去,还是抛出StackOverflowException? – Dukeling 2013-04-25 23:42:12

+0

Dukeling我已经将MAX_DEPTH设置为2,并且它似乎只是永远。事实上,在2级时,不需要检查超过36个案例...... – MrD 2013-04-25 23:43:11

回答

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