public class Solution {
public void setZeroes(int[][] matrix) {
// O(1) space solution
// The first row and the first column
boolean firstRowHasZero = false, firstColHasZero = false;
for(int j = 0; j < matrix[0].length; j++) {
if(matrix[0][j] == 0) {
firstRowHasZero = true;
break;
}
}
for(int i = 0; i < matrix.length; i++) {
if(matrix[i][0] == 0) {
firstColHasZero = true;
break;
}
}
// Rest part
for(int i = 1; i < matrix.length; i++) {
for(int j = 1; j < matrix[0].length; j++) {
if(matrix[i][j] == 0) {
matrix[0][j] = 0; // Updates the first row
matrix[i][0] = 0; // Updates the first column;
}
}
}
// Clears the matrix according to the first row and the first column
// and the two booleans
for(int i = 1; i < matrix.length; i++) {
for(int j = 1; j < matrix[0].length; j++) {
if(matrix[0][j] == 0 || matrix[i][0] == 0) {
matrix[i][j] = 0;
}
}
}
if(firstRowHasZero) {
for(int j = 0; j < matrix[0].length; j++) {
matrix[0][j] = 0;
}
}
if(firstColHasZero) {
for(int i = 0; i < matrix.length; i++) {
matrix[i][0] = 0;
}
}
}
}
Time: O(m * n)
Space: O(1)