Skip to content

Commit bf42660

Browse files
committed
Create set-matrix-zeroes.cpp
1 parent 9eea155 commit bf42660

File tree

1 file changed

+50
-0
lines changed

1 file changed

+50
-0
lines changed

C++/set-matrix-zeroes.cpp

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
// Time: O(m * n)
2+
// Space: O(1)
3+
4+
class Solution {
5+
public:
6+
void setZeroes(vector<vector<int>>& matrix) {
7+
if (matrix.empty()) {
8+
return;
9+
}
10+
11+
bool has_zero = false;
12+
int zero_i = -1, zero_j = -1;
13+
14+
for (int i = 0; i < matrix.size(); ++i) {
15+
for (int j = 0; j < matrix[0].size(); ++j) {
16+
if (matrix[i][j] == 0) {
17+
if (!has_zero) {
18+
zero_i = i;
19+
zero_j = j;
20+
has_zero = true;
21+
}
22+
matrix[zero_i][j] = 0;
23+
matrix[i][zero_j] = 0;
24+
}
25+
}
26+
}
27+
28+
if (has_zero) {
29+
for (int i = 0; i < matrix.size(); ++i) {
30+
if (i == zero_i) {
31+
continue;
32+
}
33+
for (int j = 0; j < matrix[0].size(); ++j) {
34+
if (j == zero_j) {
35+
continue;
36+
}
37+
if (matrix[zero_i][j] == 0 || matrix[i][zero_j] == 0) {
38+
matrix[i][j] = 0;
39+
}
40+
}
41+
}
42+
for (int i = 0; i < matrix.size(); ++i) {
43+
matrix[i][zero_j] = 0;
44+
}
45+
for (int j = 0; j < matrix[0].size(); ++j) {
46+
matrix[zero_i][j] = 0;
47+
}
48+
}
49+
}
50+
};

0 commit comments

Comments
 (0)