3

我设计了一个递归调用自身的函数。但是 return 语句并没有做我想做的事情。我们已经通过 print 检查了是否达到了返回值,但它并没有返回到初始函数。它输入的语句:

if(depth==0 && pb.isGoalState()){
            System.out.println("!!!!!WOOOOOW!!!!!");
            return pb;
}

println 显示得很好,但是当 pb 返回时,事情变得很奇怪。

当它回到函数时:

result = DLS(pb,depth); //never returns here!!!
System.out.println("Here: "+result.toString());

它永远不会打印出上面的打印件。我看不出有什么问题!我检查了我自己设计的其他方法。

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

        }

    private puzzleBoard DLS(puzzleBoard pb, int depth){
        System.out.println("AVskilj depth "+depth+" "+(depth==0 && pb.isGoalState()));
        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();){
                puzzleBoard tmp;
                tmp=child.next();
                tmp.printPuzzle();
                DLS(tmp,(depth-1));
            }

        }
        else
            return new puzzleBoard("999999999",0,new Vector<Integer>(),new Vector<puzzleBoard>(),new Vector<puzzleBoard>());
        return pb;
        }

所以我的问题现在仍然在这部分代码中

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

当我在 DLS(child.next(),(depth-1)); 之前不使用 return 时 它按预期遍历每个孩子,但由于缺少返回而不会存储该值。当我在它之前使用 return 时,它只会遍历迭代器中的第一个子节点并忽略其余部分,因为 return 语句终止了循环。

如何解决这个问题?我也想不出别的办法。

4

1 回答 1

3

在本次迭代中:

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

看线:

DLS(tmp,(depth-1));

DLS 返回一个puzzleBoard对象,但您不使用从该行返回的对象,因此返回的递归对象将被忽略。我没有验证您的方法的更正,但您应该从这里开始。顺便说一句,如果孩子板的数量很大,这个函数可能需要很长时间,因为你在每个孩子上调用它。

编辑:这是如何处理从 DLS 退回的板的示例:

 else if(depth>0){
       for(Iterator<puzzleBoard> child = generateSuccessorsIDS(pb).iterator(); child.hasNext();){
                    puzzleBoard tmp;
                    tmp=child.next();
                    tmp.printPuzzle();
                    puzzleBoard resultPB = DLS(tmp,(depth-1));

                    // mergre resultPB with current puzzle board (e.g. pb.addChild(resultPB));
                }

       return pb;
}
于 2012-04-08T14:08:51.760 回答