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;
}
}
}