Skip to content

Commit c07e05b

Browse files
authored
Create 0073-set-matrix-zeroes.java
1 parent cb4cbf9 commit c07e05b

File tree

1 file changed

+62
-0
lines changed

1 file changed

+62
-0
lines changed

Medium/0073-set-matrix-zeroes.java

Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,62 @@
1+
/**
2+
* Problem: 73. Set Matrix Zeroes
3+
* Difficulty: Medium
4+
* URL: https://leetcode.com/problems/set-matrix-zeroes/
5+
*
6+
* Approach:
7+
* - Use the first row and first column as markers to record which rows/columns should be zeroed.
8+
* - Track separately if the first row or first column need to be zeroed to avoid losing marker info.
9+
* - In the second pass, set entire rows/columns to zero based on these markers.
10+
*
11+
* Time Complexity: O(m * n) // each cell is visited a constant number of times
12+
* Space Complexity: O(1) // in-place, only a few extra variables
13+
*/
14+
15+
class Solution {
16+
public void setZeroes(int[][] matrix) {
17+
int m = matrix.length;
18+
int n = matrix[0].length;
19+
20+
boolean r0F = false;
21+
boolean c0F = false;
22+
23+
for (int i = 0; i < m; i++) {
24+
for (int j = 0; j < n; j++) {
25+
if (i == 0 && matrix[i][j] == 0) r0F = true;
26+
if (j == 0 && matrix[i][j] == 0) c0F = true;
27+
if (matrix[i][j] == 0) {
28+
matrix[0][j] = 0;
29+
matrix[i][0] = 0;
30+
}
31+
}
32+
}
33+
34+
for (int i = 1; i < n; i++) {
35+
if (matrix[0][i] == 0) {
36+
for (int j = 0; j < m; j++) {
37+
matrix[j][i] = 0;
38+
}
39+
}
40+
}
41+
42+
for (int i = 1; i < m; i++) {
43+
if (matrix[i][0] == 0) {
44+
for (int j = 0; j < n; j++) {
45+
matrix[i][j] = 0;
46+
}
47+
}
48+
}
49+
50+
if (r0F) {
51+
for (int i = 0; i < n; i++) {
52+
matrix[0][i] = 0;
53+
}
54+
}
55+
56+
if (c0F) {
57+
for (int i = 0; i < m; i++) {
58+
matrix[i][0] = 0;
59+
}
60+
}
61+
}
62+
}

0 commit comments

Comments
 (0)