Skip to content

Commit a7a3cd0

Browse files
authored
Merge pull request #87 from jahnvisrivastava100/patch-1
Create Set Matrix Zero
2 parents 0d72884 + 3a4236e commit a7a3cd0

File tree

1 file changed

+55
-0
lines changed

1 file changed

+55
-0
lines changed

2D Arrays/Set Matrix Zero.cpp

Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
/*______________________________________________________________________PROBLEM___________________________________________________________*/
2+
3+
/*Given an m x n matrix. If an element is 0, set its entire row and column to 0. Do it in-place.
4+
Follow up:
5+
6+
A straight forward solution using O(mn) space is probably a bad idea.
7+
A simple improvement uses O(m + n) space, but still not the best solution.
8+
Could you devise a constant space solution?
9+
10+
EXAMPLE 1:
11+
Input: matrix = [[1,1,1],[1,0,1],[1,1,1]]
12+
Output: [[1,0,1],[0,0,0],[1,0,1]]
13+
14+
EXAMPLE 2:
15+
Input: matrix = [[0,1,2,0],[3,4,5,2],[1,3,1,5]]
16+
Output: [[0,0,0,0],[0,4,5,0],[0,3,1,0]]
17+
18+
19+
20+
Constraints:
21+
22+
m == matrix.length
23+
n == matrix[0].length
24+
1 <= m, n <= 200
25+
-231 <= matrix[i][j] <= 231 - 1
26+
*/
27+
28+
29+
class Solution {
30+
public:
31+
void setZeroes(vector<vector<int>>& m) {
32+
set<int>row,col;
33+
34+
for(int i=0;i<m.size();i++){
35+
for(int j=0;j<m[0].size();j++){
36+
if(m[i][j]==0){
37+
row.insert(i);
38+
col.insert(j);
39+
}
40+
}
41+
}
42+
43+
44+
for(auto it=row.begin();it!=row.end();it++){
45+
for(int j=0;j<m[0].size();j++){
46+
m[*it][j]=0;
47+
}
48+
49+
}
50+
for(auto it=col.begin();it!=col.end();it++){
51+
for(int j=0;j<m.size();j++){
52+
m[j][*it]=0;
53+
}
54+
}
55+
}

0 commit comments

Comments
 (0)