10000 Merge pull request #6 from anushkaGurjar99/master · dnshi/Leetcode@b2a9b19 · GitHub
[go: up one dir, main page]

Skip to content

Commit b2a9b19

Browse files
authored
Merge pull request #6 from anushkaGurjar99/master
Added 73.set matrix zeros.cpp
2 parents f498070 + 4621239 commit b2a9b19

File tree

1 file changed

+77
-0
lines changed

1 file changed

+77
-0
lines changed

algorithms/setMatrixZeros.cpp

Lines changed: 77 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,77 @@
1+
2+
#include<bits/stdc++.h>
3+
using namespace std;
4+
5+
// Problem Statement: https://leetcode.com/problems/set-matrix-zeroes/
6+
7+
class Solution {
8+
public:
9+
void setZeroes(vector<vector<int>>& matrix){
10+
11+
bool firstRowZero = false;
12+
bool firstColumnZero = false;
13+
14+
// Get status
15+
markZeros(matrix, firstRowZero, firstColumnZero);
16+
17+
int row;
18+
int col;
19+
20+
// change corrosponding cell values
21+
for(row = 1; row < matrix.size(); row++){
22+
for(col = 1; col < matrix[0].size(); col++){
23+
if(matrix[row][0] == 0 || matrix[0][col] == 0)
24+
matrix[row][col] = 0;
25+
}
26+
}
27+
28+
// change 0th row and 0th col if valid
29+
if(firstRowZero){
30+
for(col = 0; col < matrix[0].size(); col++)
31+
matrix[0][col] = 0;
32+
}
33+
if(firstColumnZero){
34+
for(row = 0; row < matrix.size(); row++)
35+
matrix[row][0] = 0;
36+
}
37< 10000 code class="diff-text syntax-highlighted-line addition">+
}
38+
39+
40+
void markZeros(vector<vector<int>>& matrix, bool& firstRowZero, bool& firstColumnZero){
41+
42+
int row;
43+
int col;
44+
45+
// * get first row and col status before changing status for other cells
46+
if(matrix[0][0] == 0){
47+
firstRowZero = firstColumnZero = true;
48+
}
49+
else{
50+
for(row = 0; row < matrix[0].size(); row++){
51+
if(matrix[0][row] == 0){
52+
firstRowZero = true;
53+
break;
54+
}
55+
}
56+
57+
for(col = 0; col < matrix.size(); col++){
58+
if(matrix[col][0] == 0){
59+
firstColumnZero = true;
60+
break;
61+
}
62+
}
63+
}
64+
65+
// status for other cells
66+
for(row = 1; row < matrix.size(); row++){
67+
for(col = 1; col < matrix[0].size(); col++){
68+
69+
if(matrix[row][col] == 0){
70+
matrix[row][0] = matrix[0][col] = 0;
71+
}
72+
}
73+
}
74+
}
75+
76+
};
77+

0 commit comments

Comments
 (0)
0