Skip to content

Commit dfc24e0

Browse files
authored
Add files via upload
1 parent ecfc25d commit dfc24e0

File tree

1 file changed

+84
-0
lines changed

1 file changed

+84
-0
lines changed

SetMatrixZeroes.java

Lines changed: 84 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,84 @@
1+
// https://leetcode.com/problems/set-matrix-zeroes/
2+
public class SetMatrixZeroes {
3+
4+
//Approach: traverse through the matrix and mark those rows and cols which needs to be turned zero at 0th row and 0th col.
5+
//Also have 2 variable flags to determine if 0th row and 0th col needs to be zeored
6+
//Time: O(mn)
7+
//Space: O(1)
8+
public void setZeroes(int[][] matrix) {
9+
boolean isr=false,isc=false;
10+
for(int i=0;i<matrix.length;i++) {
11+
for(int j=0;j<matrix[0].length;j++) {
12+
if(i==0 && matrix[i][j]==0) {
13+
isr=true;
14+
}
15+
if(j==0 && matrix[i][j]==0) {
16+
isc=true;
17+
}
18+
if(i!=0 && j!=0 && (matrix[i][j]==0)) {
19+
//if {
20+
matrix[i][0]=0;
21+
matrix[0][j]=0;
22+
//}
23+
}
24+
}
25+
26+
}
27+
28+
for(int i=1;i<matrix.length;i++) {
29+
for(int j=1;j<matrix[0].length;j++) {
30+
if(matrix[i][0]==0 || matrix[0][j]==0) {
31+
matrix[i][j]=0;
32+
}
33+
}
34+
}
35+
36+
// System.out.println(isr +"--- "+isc);
37+
38+
if(isc) {
39+
int i=0;
40+
while(i<matrix.length) {
41+
matrix[i++][0]=0;
42+
}
43+
}
44+
45+
if(isr) {
46+
int j=0;
47+
while(j<matrix[0].length) {
48+
matrix[0][j]=0;
49+
j++;
50+
}
51+
}
52+
}
53+
}
54+
55+
// Apporach: we keep track of all rows and cols to be updated to zeroes
56+
//Space: O(m+n)
57+
//Time: O(mn)
58+
// public void setZeroes(int[][] matrix) {
59+
// List<Integer> rows= new ArrayList<>();
60+
// List<Integer> cols = new ArrayList<>();
61+
// for(int i=0;i<matrix.length;i++) {
62+
// for(int j=0;j<matrix[0].length;j++) {
63+
// if(matrix[i][j]==0) {
64+
// rows.add(i);
65+
// cols.add(j);
66+
// }
67+
// }
68+
// }
69+
70+
// for(int r: rows) {
71+
// for(int i=0;i<matrix[0].length;i++) {
72+
// matrix[r][i]=0;
73+
// }
74+
// }
75+
76+
// for(int c:cols) {
77+
// for(int i=0;i<matrix.length;i++) {
78+
// matrix[i][c]=0;
79+
// }
80+
// }
81+
82+
// }
83+
// }
84+

0 commit comments

Comments
 (0)