gpt4 book ai didi

java - 无限递归

转载 作者:行者123 更新时间:2023-11-29 09:03:19 24 4
gpt4 key购买 nike

我有以下代码:

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 设置新节点的深度。

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

最佳答案

您的问题不是无限递归。这可能是另外一回事。这段代码对我有用 -

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 

关于java - 无限递归,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16226417/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com