Write an algorithm such that if an element in an MxN matrix is 0, its entire row and
column are set to 0.
public void setZeros(int[][] matrix) {
boolean[] column = new boolean[matrix[0].length];
for(int i = 0; i < matrix.length; i++){
for(int j = 0; j < matrix[0].length; j++){
if(column[j]) continue;
if(matrix[i][j] == 0) {
//set i-th row and j-th col zero
for(int k = 0; k < matrix[0].length; k++){
matrix[i][k] = 0;
}
for(int k = 0; k < matrix.length; k++){
matrix[k][j] = 0;
}
//mark column and move to next row
column[j] = true;
break;
}
}
}
}
No comments:
Post a Comment