Given a m x n matrix, if an element is 0, set its entire row and column to 0. Do it in place.
There are more than one zero elements in the matrix.
The basic idea is to use the first row and column to store the information. Then we need to know whether or not to set the first row and column to zeroes. So, we use two boolean to store that information.
public class Solution {
public void setZeroes(int[][] matrix) {
int row = matrix.length;
int col = matrix[0].length;
if(col == 0 || row == 0) return;
boolean zerorow = false;
boolean zerocol = false;
for (int i = 0; i < col ; ++i) {
if(matrix[0][i] == 0)
zerorow = true;
}
for (int j = 0; j < row; ++j) {
if(matrix[j][0] == 0)
zerocol = true;
}
for (int i = 1; i < row; ++i) {
for (int j = 1; j < col ; ++j) {
if(matrix[i][j] == 0){
matrix[i][0] = 0;
matrix[0][j] = 0;
}
}
}
for (int i = 1; i < row; ++i) {
for (int j = 1; j < col ; ++j) {
if(matrix[0][j] == 0 || matrix[i][0] == 0)
matrix[i][j] = 0;
}
}
if(zerorow == true){
for (int i = 0 ;i < col ; ++i) {
matrix[0][i] = 0;
}
}
if(zerocol == true){
for (int j = 0 ;j < row ; ++j) {
matrix[j][0] = 0;
}
}
}
}