我有一个字符串的hashSet,用于表示RushHour状态。 hashSet包含所有先前访问过的状态。
我调用一个函数来返回给定状态下可用的下一个移动,并使用代码检查它们是否已被访问过:
if(!(visitedHash.contains(childBoards.get(i).Convert())))
然后,如果状态未被访问,我将其添加到队列中,使用广度优先搜索进行解决。
问题是当我写这行代码时:
if(visitedHash.contains(currentBoard.Convert())){
System.out.println("Whats Going on!!??");
}
当我推销一个新的电路板时,我得到许多州印刷“什么在继续!! ??”
这不应该是可能的!应该是?我刚刚检查了它们是否被包含在内并且它们被添加到队列中所以必须通过IF语句!
这是我搜索方法的完整代码:
public void search(Board b){
//--------Perform Breadth First Search on Board b--------//Method to solve the puzzle using Breadth First Search
System.out.println("Attempting to solve the Board using Breadth First Search...");
long startTime = System.nanoTime(); //capture the start time for the method
queue.add(b); //push the input board onto the front of the queue
while(!solved){ //while the board is not solved
currentBoard = queue.poll(); //assign the top of the queue to currentBoard
currentBoard.print(); //print the board to the screen (PRINT EVERY BOARD VISITED)
System.out.println(currentBoard.Convert());
System.out.println("This board is on level " + getLevel(currentBoard));
//System.out.println("Visited Boards size: " + visitedHash.size());
if(visitedHash.contains(currentBoard.Convert())){
System.out.println("Whats Going on!!??");
}
boardsExplored++; //increment the number of boardsExplored
if(currentBoard.isGoal()){ //if the board is the goal state
long endTime = System.nanoTime(); //capture the end time for the method
long duration = endTime - startTime; //calculate the duration for the method
time = (double)duration / 1000000000.0; //convert the time to seconds
System.out.println("SOLVED! Goal car is Free!");
System.out.println("Time taken to solve = " + time + " seconds"); //print the time taken in seconds
System.out.println("Moves made = " + (boardsExplored - 1)); //print the number of boards explored to reach goal
visitedHash.add(currentBoard.Convert()); //add the board (when converted to a string) to the list of visited boards
printSolution(currentBoard); //Call method to print shortest path found
write(b); //Call method to write data to the file
solved = true; //set solved to true
return; //exit the loop
}
visitedHash.add(currentBoard.Convert()); //add the board (when converted to a string) to the list of visited boards
childBoards = currentBoard.getChildMoves(); //call getChildMoves on the currentBoard to retrieve all available boards
for (int i = 0 ; i < childBoards.size() ; i ++){ //for every one of the child boards
if(!(visitedHash.contains(childBoards.get(i).Convert()))){ //if the child board has NOT previously been visited
queue.add(childBoards.get(i)); //add the child board to the queue and loop back
parent.put(childBoards.get(i), currentBoard); //Map the child board to its parent
level.put(childBoards.get(i), getLevel(currentBoard));
}
}
}
}
答案 0 :(得分:0)
正如其他人在评论中提到的那样,你可能需要为Convert()的返回类型创建一个合适的hashCode和equals方法。