-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy path16_set-matrix-zeroes.cpp
More file actions
68 lines (58 loc) · 1.56 KB
/
16_set-matrix-zeroes.cpp
File metadata and controls
68 lines (58 loc) · 1.56 KB
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
// DATE: 29-July-2023
/* PROGRAM: 16_Matrix - Set Matrix Zeroes
https://leetcode.com/problems/set-matrix-zeroes/
G*/
// @ankitsamaddar @July_2023
#include <iostream>
#include <vector>
using namespace std;
class Solution {
public:
void setZeroes(vector<vector<int>>& matrix) {
int rows = matrix.size(), cols = matrix[0].size();
bool fillFirstRow = false;
bool fillFirstCol = false;
// mark the matrix to add zero
for (int r = 0; r < rows; r++) {
for (int c = 0; c < cols; c++) {
if (matrix[r][c] == 0) {
// set the flags to handle first row & column
if (r == 0) fillFirstRow = true;
if (c == 0) fillFirstCol = true;
// mark first column of match to 0
matrix[0][c] = 0;
// mark first rows of match to 0
matrix[r][0] = 0;
}
}
}
// add zeros to the internal matrix (except the first row & column)
for (int r = 1; r < rows; r++) {
for (int c = 1; c < cols; c++) {
// using mark to add zeros
if (matrix[r][0] == 0 || matrix[0][c] == 0) {
matrix[r][c] = 0;
}
}
}
// add zero to the first column
if (fillFirstCol)
for (int r = 1; r < rows; r++) matrix[r][0] = 0;
// add zero to the first row
if (fillFirstRow) {
for (int c = 0; c < cols; c++) matrix[0][c] = 0;
}
}
};
int main() {
vector<vector<int>> nums = {{0,1,2,0},{3,4,5,2},{1,3,1,5}};
Solution sol;
sol.setZeroes(nums);
for(auto row:nums){
for(int col:row){
cout<<col<<" ";
}
cout<<endl;
}
return 0;
}