-4
所以我的代碼適用於基本的8拼圖問題,但是當我用較難拼圖配置測試時,它會運行到無限循環。有人可以編輯我的代碼,以防止這種情況發生。請注意,我已包含防止循環或循環的代碼。我嘗試了包括迭代深度優先搜索技術,但這也不起作用。有人可以查看我的代碼。防止深度優先搜索算法陷入無限循環,8拼圖
/** Implementation for the Depth first search algorithm */
static boolean depthFirstSearch(String start, String out){
LinkedList<String> open = new LinkedList<String>();
open.add(start);
Set<String> visitedStates = new HashSet<String>(); // to prevent the cyle or loop
LinkedList<String> closed = new LinkedList<String>();
boolean isGoalState= false;
while((!open.isEmpty()) && (isGoalState != true)){
String x = open.removeFirst();
System.out.println(printPuzzle(x)+"\n\n");
jtr.append(printPuzzle(x) +"\n\n");
if(x.equals(out)){ // if x is the goal
isGoalState = true;
break;
}
else{
// generate children of x
LinkedList<String> children = getChildren(x);
closed.add(x); // put x on closed
open.remove(x); // since x is now in closed, take it out from open
//eliminate the children of X if its on open or closed ?
for(int i=0; i< children.size(); i++){
if(open.contains(children.get(i))){
children.remove(children.get(i));
}
else if(closed.contains(children.get(i))){
children.remove(children.get(i));
}
}
// put remaining children on left end of open
for(int i= children.size()-1 ; i>=0 ; i--){
if (!visitedStates.contains(children.get(i))) { // check if state already visited
open.addFirst(children.get(i)); // add last child first, and so on
visitedStates.add(children.get(i));
}
}
}
}
return true;
}
你需要學習如何調試你自己的代碼。從這裏開始:https://ericlippert.com/2014/03/05/how-to-debug-small-programs/ – shmosel
我請求某人查看算法,而不是讓某人告訴我調試我自己的代碼。你錯了。 –
你不能總是得到你要求的。即使你這麼做,從長遠來看,它也無濟於事。學習調試自己的代碼是您需要有效編碼的最關鍵的技能之一。 – shmosel