读取二维数组的问题 - Java

Issues with reading a 2d Array - Java

我正在尝试使用二维数组进行 Conway 的人生游戏。该方法应该查看二维数组上的每个位置并检查其每个邻居并计算该位置周围有多少邻居(0 为空,1 为占用)。然后它执行一些逻辑并决定该位置是死的还是活的。我遇到的问题是,当它检查第二个位置时,tempMatrix 的值是错误的。我一直在检查第一个位置 [0][0],它从 0 变为 1,我不知道为什么。预先感谢您的帮助!

public static int[][] Evolve(int[][] _array){
    inputMatrix = _array;
    outputMatrix = inputMatrix;
    int [][] tempMatrix = inputMatrix;
    System.out.println("Output Matrix:");
    for (int x = 0; x < size; x++){
        for (int y = 0; y < size; y++){
            int neighbor_count = 0;
            ArrayList<int[]> neighbors = getNeighbors(x,y);
            for(int[] neighbor: neighbors){
                int tempX = neighbor[0];
                int tempY = neighbor[1];
                int temp = tempMatrix[tempX][tempY];
                if(temp == 1){
                    neighbor_count++;
                }
            }
            if(tempMatrix[x][y] == 1){
                if(neighbor_count == 1 || neighbor_count > 3) {
                    outputMatrix[x][y] = 0;
                }
                else{
                    outputMatrix[x][y] = 1;
                }
            }else if(neighbor_count == 3){
                outputMatrix[x][y] = 1;
            }else{
                outputMatrix[x][y] = 0;
            }
            System.out.printf("%2d ",outputMatrix[x][y]);
        }
        System.out.println();
    }
    return outputMatrix;
}

您的 inputMatrix outputMatrixtempMatrix 指的是同一个二维数组。 因此,当你通过以下代码修改outputMatrix

if(tempMatrix[x][y] == 1){
            if(neighbor_count == 1 || neighbor_count > 3) {
                outputMatrix[x][y] = 0;
            }
            else{
                outputMatrix[x][y] = 1;
            }
        }else if(neighbor_count == 3){
            outputMatrix[x][y] = 1;
        }else{
            outputMatrix[x][y] = 0;
        }

tempMatrix 的值也发生了变化。 因此,尝试为所有三个矩阵创建新的二维数组,然后复制值。

int inputMatrix[][]=new int[dimension][dimension];

现在将 _array 矩阵的值复制到 inputMatrix