我正在尝试使用启发式搜索来解决 8 谜题问题。我使用 3*3 矩阵来表示可能性。代码并不完整,但是当我尝试将探索的元素添加到探索的集合(这是一个 ArrayList)时,它只更新探索的集合中的当前元素,而不是在末尾添加一个元素。当我尝试打印探索集中的所有元素时,始终只有一个元素(每次迭代都会更新)。我想知道我的代码有什么问题。谢谢你!!
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);
最佳答案
您的代码不完整,但立即引人注目的一件事是您同时向探索列表添加和删除元素。请参阅下面的评论:
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);
关于java - ArrayList添加不增加列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54871794/