我正在尝试使用启发式搜索解决8难题问题。我正在使用3 * 3矩阵表示可能性。代码并不完整,但是当我尝试将explored元素添加到explored set(它是一个ArrayList)中时,它仅更新explicit set中的当前元素,而不是在末尾添加一个元素。当我尝试打印探索集中的所有元素时,总是只有一个元素(每次迭代都会更新)。我想知道我的代码有什么问题。谢谢!!
public static void printexplored(ArrayList<int[][]> explored){
//System.out.println("the size of the explored set is " + explored.size());
System.out.println("the explored set is...");
while(explored.isEmpty() == false){
int[][] temp = explored.remove(0);
for(int i = 0; i < 3; i++){
for(int j = 0; j < 3; j++){
System.out.print(temp[i][j]);
}
System.out.println();
}
System.out.println();
}
}
public static boolean heuristicSearch(int initialState[][]){
Queue<int[][]> frontier = new LinkedList<int[][]>();
frontier.add(initialState);
ArrayList<int[][]> explored = new ArrayList<int[][]>();
int f_score = 0;
//int count = 0;
while(frontier.isEmpty() == false){
int[][] temporaryState = new int[3][3];
temporaryState = frontier.remove();
int indexX = blankIndexX(temporaryState);
int indexY = blankIndexY(temporaryState);
explored.add(temporaryState);
printexplored(explored);
答案 0 :(得分:1)
您的代码是不完整的,但立即引起注意的一件事是您正在同时添加和删除元素到浏览列表中。查看以下评论:
public static void printexplored(ArrayList<int[][]> explored){
//System.out.println("the size of the explored set is " + explored.size());
System.out.println("the explored set is...");
while(explored.isEmpty() == false){
//---->YOU REMOVED THE ELEMENT WHICH WAS ADDED EARLIER HERE:
int[][] temp = explored.remove(0);
for(int i = 0; i < 3; i++){
for(int j = 0; j < 3; j++){
System.out.print(temp[i][j]);
}
System.out.println();
}
System.out.println();
}
}
public static boolean heuristicSearch(int initialState[][]){
Queue<int[][]> frontier = new LinkedList<int[][]>();
frontier.add(initialState);
ArrayList<int[][]> explored = new ArrayList<int[][]>();
int f_score = 0;
//int count = 0;
while(frontier.isEmpty() == false){
int[][] temporaryState = new int[3][3];
temporaryState = frontier.remove();
int indexX = blankIndexX(temporaryState);
int indexY = blankIndexY(temporaryState);
//---->YOU ARE ADDING AN ELEMENT HERE BUT REMOVING IT LATER IN THE THE
//printexplored METHOD:
explored.add(temporaryState);
printexplored(explored);
答案 1 :(得分:1)
在打印方法中,您将从列表中删除元素。
要解决此问题,请在printexplored()
方法中替换以下几行:
while(explored.isEmpty() == false){
int[][] temp = explored.remove(0);
为此:
for (int i = 0; i < explored.size(); i++) {
int[][] temp = explored.get( i );