Skip to content

Commit 0b8e472

Browse files
committed
Set Matrix Zeros
1 parent 836d3a2 commit 0b8e472

File tree

1 file changed

+32
-0
lines changed

1 file changed

+32
-0
lines changed

set-matrix-zeroes/TonyKim9401.java

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
// TC: O(n^2)
2+
// SC: O(1)
3+
class Solution {
4+
public void setZeroes(int[][] matrix) {
5+
boolean firstRow = false, firstCol = false;
6+
7+
for (int i = 0; i < matrix.length; i++) {
8+
for (int j = 0; j < matrix[0].length; j++) {
9+
if (matrix[i][j] == 0) {
10+
if (i == 0) firstRow = true;
11+
if (j == 0) firstCol = true;
12+
matrix[0][j] = 0;
13+
matrix[i][0] = 0;
14+
}
15+
}
16+
}
17+
18+
for (int i = 1; i < matrix.length; i++) {
19+
for (int j = 1; j < matrix[0].length; j++) {
20+
if (matrix[i][0] == 0 || matrix[0][j] == 0) matrix[i][j] = 0;
21+
}
22+
}
23+
24+
if (firstRow) {
25+
for (int j = 0; j < matrix[0].length; j++) matrix[0][j] = 0;
26+
}
27+
28+
if (firstCol) {
29+
for (int i = 0; i < matrix.length; i++) matrix[i][0] = 0;
30+
}
31+
}
32+
}

0 commit comments

Comments
 (0)