Search code examples
javaarraysloopsmatrix

How Matrix Elements are getting changed?


1

My Question is when I am initializing matrix2 with case1 approach I am getting the right answer, but when I am initialising matrix 2 with case2 approach I am getting wrong ans.

The if condition is executing on matrix[1][2], I am not able to understand where I am making a mistake

int matrix[][] = {{1,1,1},{1,0,1},{1,1,1}};

    CASE 1 - int matrix2[][]= {{1,1,1},{1,0,1},{1,1,1}};

    CASE 2 - int matrix2[][]=matrix;

    System.out.println(Arrays.deepToString(matrix2));
     for(int i=0;i<matrix.length;i++){
        for(int j=0;j<matrix[i].length;j++){
            if(matrix[i][j]==0){

                // making col= 0
                for(int k=0;k<matrix2.length;k++){
                    matrix2[k][j]=0;
                }

                // making row = 0
                for(int k=0;k<matrix2.length;k++){
                    matrix2[i][k]=0;
                }
                
            }
        }
        System.out.println(Arrays.toString(matrix[i]));
    }
    System.out.println(Arrays.deepToString(matrix2));

I am initialising it with case2 as in LEETCODE matrix will be different each time


Solution

  • Case 2 is not copying the values into matrix2. Instead both matrix and matrix2 variables are pointing to same memory. So any change in matrix2 or matrix will look like changing in both. Even though array holds Primitive types, internally it allocates memory just like any other Java Objects.

    int matrix[][] = {{1,1,1},{1,0,1},{1,1,1}};

    int matrix2[][]=matrix;

    enter image description here

    Solution: Do a deep copy / clone the array. Creates a independent copy in memory, so any change in matrix2 or matrix will not affect each other.

    int matrix[][] = {{1,1,1},{1,0,1},{1,1,1}};

    int matrix2[][] = Arrays.stream(matrix) .map(int[]::clone) .toArray(int[][]::new);

    enter image description here