-
-
Notifications
You must be signed in to change notification settings - Fork 164
/
Copy pathSetMatrixZeros.java
53 lines (46 loc) · 1.35 KB
/
SetMatrixZeros.java
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
package java1.algorithms.matrix;
import java.util.*;
public class SetMatrixZeros {
//TC: O(rows*cols) SC:O(1)
private static void setZeros(int[][] matrix) {
int rows = matrix.length, cols = matrix[0].length;
boolean rowZero = false;
//Determine which rows/columns needs to be set to zero
for(int r=0; r< rows; r++) {
for(int c=0; c<cols; c++) {
if(matrix[r][c] == 0) {
matrix[0][c] = 0;
if(r >0) {
matrix[r][0] = 0;
} else {
rowZero = true;
}
}
}
}
for(int r=1; r<rows; r++) {
for(int c=1; c<cols; c++) {
if(matrix[0][c] == 0 || matrix[r][0] == 0) {
matrix[r][c] = 0;
}
}
}
if(matrix[0][0] == 0) {
for(int r=0; r<rows; r++) {
matrix[r][0] = 0;
}
}
if(rowZero) {
for(int c=0; c<cols; c++) {
matrix[0][c] = 0;
}
}
}
public static void main(String[] args) {
int[][] matrix = {
{1, 0, 1}, {1, 0, 1}, {0, 1, 1}
};
setZeros(matrix);
System.out.println(Arrays.deepToString(matrix));
}
}