0

I am writing some code to set all the values in the rows and columns of a matrix to zero if any row or column in the matrix has a zero.

In my code, I have copied the elements into another array called copy[][] and modified the elements in copy[][], thus keeping the actual array array[][] unmodified.

However, I can see that even array[][] is getting modified. I can see the value of elements in array[][] changing during debug mode, but I have been unable to figure out how this is happening.

Can someone please help?

For reference, here is the code I am working on:

import java.util.Arrays;
import java.util.Scanner;

public class MatrixZero {

static int copy[][];

public static void main(String[] args) {
    // TODO Auto-generated method stub

    System.out.println("Enter the number of rows and columns: ");
    Scanner scanner = new Scanner(System.in);
    int m = scanner.nextInt();
    int n = scanner.nextInt();
    System.out.println("Enter the elements of the matrix:");
    int array[][] = new int[m][n];
    for(int i=0;i<m;i++){
        for(int j=0;j<n;j++){
            array[i][j] = scanner.nextInt();
        }
    }
    //copy the array to another array
    copy = Arrays.copyOf(array,array.length);
    System.out.println("The array copied is: ");
    for(int i=0;i<m;i++){
        for(int j=0;j<n;j++){
            System.out.print(copy[i][j]+"  ");
        }
        System.out.println("\n");
    }
    //Code to make the entire row and column of a matrix zero if
    //any one element is zero
    for(int i=0;i<m;i++){
        for(int j=0;j<n;j++){
            if(array[i][j]==0){
                //call a method to make the entire row and column zero
                makeZero(i, j,n);
            }
        }
    }

    System.out.println("The final matrix: ");
    for(int i=0;i<m;i++){
        for(int j=0;j<n;j++){
            System.out.print(copy[i][j]+"  ");
        }
        System.out.println("\n");
    }
    scanner.close();

}

public static void makeZero(int row,int column,int n){



    for(int i=0;i<n;i++){
        copy[row][i] = 0;
        //copy[i][column] = 0;
    }
    for(int i=0;i<n;i++){
        copy[i][column] = 0;
    }
}

}
Vishwa Bhat
  • 77
  • 11
  • have you tried with this `if(copy[i][j]==0){ makeZero(i, j,n); }` – Rajith Pemabandu Aug 13 '17 at 02:45
  • I got the solution. Thank you all :) The issue is that when you use Arrays.copyOf or use clone on an multi dimensional array the new variable created will only be a shallow copy. That means that it will be still be pointing to the same reference in the memory. So if the copy is changed so will the initial variable. The only way to do this it to iterate over the list and copy the values manually. – Vishwa Bhat Aug 13 '17 at 04:12

0 Answers0