-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSetMatrixZeros.java
More file actions
79 lines (68 loc) · 1.98 KB
/
SetMatrixZeros.java
File metadata and controls
79 lines (68 loc) · 1.98 KB
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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
package ArraysD2;
public class SetMatrixZeros {
static private boolean[][] isVisited;
public static void set(int[][] matrix, int i, int j) {
if (isVisited[i][j]) return;
isVisited[i][j] = true;
// Go up in a column.
int temp = j;
while (temp >= 0) {
if (matrix[i][temp] == 0) {
temp--;
continue;
}
matrix[i][temp] = 0;
isVisited[i][temp--] = true;
}
// Go down in a column.
temp = j;
while (temp < matrix[0].length) {
if (matrix[i][temp] == 0) {
temp++;
continue;
}
matrix[i][temp] = 0;
isVisited[i][temp++] = true;
}
// Go left in a column.
temp = i;
while (temp >= 0) {
if (matrix[temp][j] == 0) {
temp--;
continue;
}
matrix[temp][j] = 0;
isVisited[temp--][j] = true;
}
// Go right in a column.
temp = i;
while (temp < matrix.length) {
if (matrix[temp][j] == 0) {
temp++;
continue;
}
matrix[temp][j] = 0;
isVisited[temp++][j] = true;
}
}
public static void setZeroes(int[][] matrix) {
isVisited = new boolean[matrix.length][matrix[0].length];
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[0].length; j++) {
if (matrix[i][j] == 0) {
set(matrix, i, j);
}
}
}
}
public static void main(String[] args) {
int[][] matrix = {{0, 3, 4, 0}, {1, 2, 3, 4}, {2, 3, 4, 5}};
setZeroes(matrix);
for (int[] num : matrix) {
for (int j = 0; j < matrix[0].length; j++) {
System.out.print(num[j] + " ");
}
System.out.println();
}
}
}