gpt4 book ai didi

java - java中Integer[][](矩阵)的Arraylist

转载 作者:行者123 更新时间:2023-11-30 08:18:38 24 4
gpt4 key购买 nike

我在 Java 中定义了一个矩阵 (Integer[][]) 的 ArrayList。当我向 ArrayList 添加新矩阵时,它会将所有变量更改为最后一个矩阵。

我的意思是当我添加

0 4 4 2
0 4 4 2
1 2 3 4
4 5 9 7

然后添加

1 4 7 8
0 1 2 3
4 5 6 7
4 1 2 3

当我打印这样的元素时:

1 4 7 8
0 1 2 3
4 5 6 7
4 1 2 3
-------
1 4 7 8
0 1 2 3
4 5 6 7
4 1 2 3

那么我应该为此做什么呢?这是我的代码:

private Integer matrix[][] = new Integer[4][4];

public Integer[][] right(Integer[][] M) {
for (int k = 0; k < 4; k++)
for (int i = 0; i < 4; i++)
for (int j = 0; j < 3; j++) {
if (M[i][j] != 0 && M[i][j + 1] == 0) {
M[i][j + 1] += M[i][j];
M[i][j] = 0;
new_tile = true;
}
}
for (int i = 0; i < 4; i++)
for (int j = 3; j > 0; j--) {
if (M[i][j] == M[i][j - 1] && M[i][j] != 0 && M[i][j - 1] != 0) {
M[i][j] += M[i][j - 1];
M[i][j - 1] = 0;
new_tile = true;
}
}
for (int k = 0; k < 4; k++)
for (int i = 0; i < 4; i++)
for (int j = 0; j < 3; j++) {
if (M[i][j] != 0 && M[i][j + 1] == 0) {
M[i][j + 1] += M[i][j];
M[i][j] = 0;
new_tile = true;
}
}
return M;
}


static void printMatrix(Integer[][] matrix) {
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[0].length; j++) {
System.out.print(matrix[i][j]);
}
System.out.println();
}
}

/**
* Print the elements in a matrix list
*/
static void printMatrices(ArrayList<Integer[][]> matrices) {
for (Integer[][] matrix : matrices) {
printMatrix(matrix);
System.out.println("--------");
}
}
public void solve() {

Integer[][] temp = right(matrix);
printMatrix(temp);
if (new_tile)
visited_nodes.add(temp);
else {
printMatrices(visited_nodes);
}
refresh();
}

@Override
public void actionPerformed(ActionEvent e) {

solve();
repaint();
}

每 100 毫秒调用一次求解方法。

最佳答案

您实际上总是修改相同的矩阵实例。

更改right()方法,使其在每次调用时创建一个新矩阵:

public Integer[][] right(Integer[][] M) {
Integer[][] newM = new Integer[4][4];

// modify newM in your algo instead of M
// Showing only the first bloc
for (int k = 0; k < 4; k++)
for (int i = 0; i < 4; i++)
for (int j = 0; j < 3; j++) {
if (M[i][j] != 0 && M[i][j + 1] == 0) {
newM[i][j + 1] = M[i][j + 1] + M[i][j];
newM[i][j] = 0;
new_tile = true;
}
}
//...
return newM;
}

关于java - java中Integer[][](矩阵)的Arraylist,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29305102/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com