【问题标题】:An ArrayList is not being updated properlyArrayList 未正确更新
【发布时间】:2020-04-09 11:49:21
【问题描述】:

所以我正在做一个家庭作业,对于我们编写的其中一种方法,我们应该创建一个可迭代对象,该对象具有所有可能导致移位 0 的 3x3 板。这些板被添加到 ArrayList 以便稍后迭代.与董事会:

0 1 3 
4 2 5 
7 8 6 

我应该得到

4 1 3 
0 2 5 
7 8 6 

1 0 3 
4 2 5 
7 8 6,

但我得到了

1 0 3 
4 2 5 
7 8 6 

1 0 3 
4 2 5 
7 8 6.

我也尝试过使用堆栈和推送,但结果相同。我完全不知道是什么原因造成的,所以有人可以给我一个建议吗?

public class Board {
private int[][] myTiles;
private int N;

// create a board from an n-by-n array of tiles,
// where tiles[row][col] = tile at (row, col)
public Board(int[][] tiles){
    myTiles = tiles;
    N = myTiles[0].length;

private static void exch(int[][] comp, int row1, int col1, int row2, int col2){
    int copy = comp[row1][col1];
    comp[row1][col1]=comp[row2][col2];
    comp[row2][col2]=copy;
}

public Iterable<Board> neighbors(){
    ArrayList<Board> boards = new ArrayList<>();
    int[][] comp = myTiles;
    int row=0;
    int col=0;

    for(int i=0; i<N; i++){
        for(int j=0; j<N; j++){
            if(myTiles[i][j]==0){
                row=i;
                col=j;
            }
        }
    }
    System.out.println("row: " + row + " col: " + col);
    System.out.println(" ");
    if(row>0){
        exch(comp,row,col,row-1,col);
        boards.add(new Board(comp));
        exch(comp,row,col,row-1,col);
    }
    if(row<(N-1)){
        exch(comp,row,col,row+1,col);
        boards.add(new Board(comp));
        exch(comp,row,col,row+1,col);
    }
    if(col>0){
        exch(comp,row,col,row,col-1);
        boards.add(new Board(comp));
        exch(comp,row,col,row,col-1);
    }
    if(col<(N-1)){
        exch(comp,row,col,row,col+1);
        boards.add(new Board(comp));

    }
    for (Board b : boards) {
        System.out.println((b.toString());
    }
    return boards;
}

【问题讨论】:

  • 定义“移零”。

标签: java algorithm arraylist


【解决方案1】:

你的板是假的。它们都具有相同的底层myTiles,因为构造函数说:

myTiles = tiles;

与 C++ 不同,这只会创建对同一 tiles 数组的引用。

使用循环进行深度复制以迭代值,您应该没问题。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-10-26
    • 2021-11-03
    • 2018-01-20
    • 2013-04-02
    • 2017-03-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多