1
class Solution {
2
public void setZeroes(int[][] matrix) {
3
if (matrix == null || matrix.length == 0 || matrix[0].length == 0) return;
4

5
int row = matrix.length;
6
int col = matrix[0].length;
7

8
boolean firstColumnZero = false;
9
boolean firstRowZero = false;
10

11
// Check if first column should be made zero
12
for (int i = 0; i < row; i++) {
13
if (matrix[i][0] == 0) {
14
firstColumnZero = true;
15
break;
16
}
17
}
18

19
// Check if first row should be made zero
20
for (int i = 0; i < col; i++) {
21
if (matrix[0][i] == 0) {
22
firstRowZero = true;
23
break;
24
}
25
}
26

27
// Traverse the matrix excluding first row and column
28
// If zero is found, update the same in first row and column
29

30
for (int i = 1; i < row; i++) {
31
for (int j = 1; j < col; j++) {
32
if (matrix[i][j] == 0) {
33
matrix[i][0] = 0;
34
matrix[0][j] = 0;
35
}
36
}
37
}
38

39
// Now traverse again and update
40
for (int i = 1; i < row; i++) {
41
for (int j = 1; j < col; j++) {
42
if (matrix[i][0] == 0 || matrix[0][j] == 0) {
43
matrix[i][j] = 0;
44
}
45
}
46
}
47

48
// Traverse and update first column
49
if (firstColumnZero) {
50
for (int i = 0; i < row; i++) {
51
matrix[i][0] = 0;
52
}
53
}
54

55
// Traverse and update first row
56
if (firstRowZero) {
57
for (int j = 0; j < col; j++) {
58
matrix[0][j] = 0;
59
}
60
}
61
}
62
}

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0