【发布时间】: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;
}
【问题讨论】:
-
定义“移零”。