-
Notifications
You must be signed in to change notification settings - Fork 0
/
markZeroes_Better.cpp
91 lines (78 loc) · 1.66 KB
/
markZeroes_Better.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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
// if matrix conatins zero mark the entire row and column as zero.
// Uses Optimal Method
// Link: https://leetcode.com/problems/set-matrix-zeroes/
#include <bits/Stdc++.h>
using namespace std;
void setZeroes(vector<vector<int>> &matrix)
{
int numRows = matrix.size();
int numCols = matrix[0].size();
int col0 = 1;
for (int i = 0; i < numRows; i++)
{
for (int j = 0; j < numCols; j++)
{
if (matrix[i][j] == 0)
{
matrix[i][0] = 0;
if (j != 0)
matrix[0][j] = 0;
else
col0 = 0;
}
}
}
for (int i = 1; i < numRows; i++)
{
for (int j = 1; j < numCols; j++)
{
if (matrix[i][j] != 0)
{
if (matrix[0][j] == 0 || matrix[i][0] == 0)
{
matrix[i][j] = 0;
}
}
}
}
if (matrix[0][0] == 0)
{
for (int j = 0; j < numCols; j++)
{
matrix[0][j] = 0;
}
}
if (col0 == 0)
{
for (int i = 0; i < numRows; i++)
{
matrix[i][0] = 0;
}
}
}
int main()
{
vector<vector<int>> matrix = {
{1, 2, 3},
{4, 0, 6},
{7, 8, 9}};
for (auto row : matrix)
{
for (int elem : row)
{
cout << elem << " ";
}
cout << endl;
}
cout << "After Setting" << endl;
setZeroes(matrix);
for (auto row : matrix)
{
for (int elem : row)
{
cout << elem << " ";
}
cout << endl;
}
return 0;
}