forked from Divya063/LeetCode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
set-matrix-zeroes.cpp
50 lines (46 loc) · 1.38 KB
/
set-matrix-zeroes.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
// Time: O(m * n)
// Space: O(1)
class Solution {
public:
void setZeroes(vector<vector<int>>& matrix) {
if (matrix.empty()) {
return;
}
bool has_zero = false;
int zero_i = -1, zero_j = -1;
for (int i = 0; i < matrix.size(); ++i) {
for (int j = 0; j < matrix[0].size(); ++j) {
if (matrix[i][j] == 0) {
if (!has_zero) {
zero_i = i;
zero_j = j;
has_zero = true;
}
matrix[zero_i][j] = 0;
matrix[i][zero_j] = 0;
}
}
}
if (has_zero) {
for (int i = 0; i < matrix.size(); ++i) {
if (i == zero_i) {
continue;
}
for (int j = 0; j < matrix[0].size(); ++j) {
if (j == zero_j) {
continue;
}
if (matrix[zero_i][j] == 0 || matrix[i][zero_j] == 0) {
matrix[i][j] = 0;
}
}
}
for (int i = 0; i < matrix.size(); ++i) {
matrix[i][zero_j] = 0;
}
for (int j = 0; j < matrix[0].size(); ++j) {
matrix[zero_i][j] = 0;
}
}
}
};