ArrayList添加不会增加列表



我正在尝试使用启发式搜索来解决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);

在您的打印方法中,您正在从列表中删除元素。
要修复,请在printexplored()方法中替换以下行:

        while(explored.isEmpty() == false){
            int[][] temp = explored.remove(0);

为此:

        for (int i = 0; i < explored.size(); i++) {
            int[][] temp = explored.get( i );

最新更新