-
Notifications
You must be signed in to change notification settings - Fork 12
/
solution_constant_space.cpp
71 lines (64 loc) · 1.85 KB
/
solution_constant_space.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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
#include <vector>
#include <iostream>
using namespace std;
class Solution {
public:
void setZeroes(vector<vector<int>>& matrix) {
int rows = matrix.size();
if (rows == 0) {
return;
}
int cols = matrix[0].size();
// check if first row contains a zero
bool first_zero = false;
for (int i = 0; i < cols; ++i) {
if (matrix[0][i] == 0) {
first_zero = true;
}
}
// put zeroes in first row if the column has zero
for (int j = 0; j < cols; ++j) {
for (int i = 0; i < rows; ++i) {
if (matrix[i][j] == 0) {
matrix[0][j] = 0;
}
}
}
// set zeroes in the matrix
for (int i = 1; i < rows; ++i) {
// check if row has zero
bool row_zero = false;
for (int j = 0; j < cols; ++j) {
if (matrix[i][j] == 0) {
row_zero = true;
}
}
// if row has zero or the first row's particular element has zero
for (int j = 0; j < cols; ++j) {
if (matrix[0][j] == 0 || row_zero) {
matrix[i][j] = 0;
}
}
}
// put zeroes in the first row only if first_zero is true
if (first_zero) {
for (int i = 0; i < cols; ++i) {
matrix[0][i] = 0;
}
}
}
};
int main () {
Solution solver;
vector<vector<int> > matrix = {{0, 1, 2, 0},
{3, 4, 5, 2},
{1, 3, 1, 5}};
solver.setZeroes(matrix);
for (auto row: matrix) {
for (auto x: row) {
cout << x << " ";
}
cout << endl;
}
return 0;
}