Skip to content

Commit 34e6d77

Browse files
MEDIUM/src/medium/SetMatrixZeroes.java
1 parent 926b9e2 commit 34e6d77

File tree

1 file changed

+23
-0
lines changed

1 file changed

+23
-0
lines changed
+23
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
package medium;
2+
3+
public class SetMatrixZeroes {
4+
//this is the most straightforward solution which uses O(mn) space
5+
public void setZeroes(int[][] matrix) {
6+
if(matrix == null || matrix.length == 0) return;
7+
int height = matrix.length, width = matrix[0].length;
8+
boolean[][] zero = new boolean[height][width];
9+
for(int i = 0; i < height; i++){
10+
for(int j = 0; j < width; j++){
11+
if(matrix[i][j] == 0) zero[i][j] = true;
12+
}
13+
}
14+
for(int i = 0; i < height; i++){
15+
for(int j = 0; j < width; j++){
16+
if(zero[i][j]){
17+
for(int k = 0; k < height; k++) matrix[k][j] = 0;
18+
for(int k = 0; k < width; k++) matrix[i][k] = 0;
19+
}
20+
}
21+
}
22+
}
23+
}

0 commit comments

Comments
 (0)