我在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;
}