我在Java中有一个for循环问题。我正在尝试进行迭代式深层搜索,并且在深度n处生成子代的代码如下所示:

for(Iterator<puzzleBoard> child = generateSuccessorsIDS(pb).iterator(); child.hasNext();){
    DLS(child.next(),(depth-1));
}


当不使用return语句时,DLS会像应做的那样执行操作,但是由于缺少return语句,该值未到达调用函数。使用return DLS(...)时,它仅返回迭代器生成的第一个值。如何解决呢?我粘贴了整个DLS及其下面的调用者函数。

private puzzleBoard IDS(String initial){
    puzzleBoard pb = new puzzleBoard(initial,0,new Vector<Integer>(),new Vector<puzzleBoard>(),new Vector<puzzleBoard>());

    puzzleBoard result=new puzzleBoard("999999999",0,new Vector<Integer>(),new Vector<puzzleBoard>(),new Vector<puzzleBoard>());
    for(int depth=0;depth<3;depth++){//Repeat
        System.out.println("DP "+depth);
        result = DLS(pb,depth);
        System.out.println("Here: "+result.toString());
        if(result.isGoalState())
            return result;
    }
    return new puzzleBoard("999999999",0,new Vector<Integer>());
}

private puzzleBoard DLS(puzzleBoard pb, int depth){

    pb.printPuzzle();
    if(depth==0 && pb.isGoalState()){
        System.out.println("!!!!!WOOOOOW!!!!!");
        return pb;
    }
    else if(depth>0){
        for(Iterator<puzzleBoard> child = generateSuccessorsIDS(pb).iterator(); child.hasNext();){
            DLS(child.next(),(depth-1));
        }
    }
    else
        return new puzzleBoard("999999999",0,new Vector<Integer>(),new Vector<puzzleBoard>(),new Vector<puzzleBoard>());
    return pb;
}

最佳答案

可能是我错了,但我认为您应该将for循环放在外面,实际上是第一次调用函数DLS(puzzleBoard pb, int depth)的地方.....在内部else if仅调用DLS(pb,depth);

07-27 15:14