-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsetmatrixzero4.java
More file actions
71 lines (62 loc) · 2.3 KB
/
setmatrixzero4.java
File metadata and controls
71 lines (62 loc) · 2.3 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
import java.util.*;
public class setmatrixzero4 {
static ArrayList<ArrayList<Integer>> zeroMatrix(ArrayList<ArrayList<Integer>> matrix, int n, int m) {
// int[] row = new int[n]; --> matrix[..][0]
// int[] col = new int[m]; --> matrix[0][..]
int col0 = 1;
// step 1: Traverse the matrix and
// mark 1st row & col accordingly:
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
if (matrix.get(i).get(j) == 0) {
// mark i-th row:
matrix.get(i).set(0, 0);
// mark j-th column:
if (j != 0)
matrix.get(0).set(j, 0);
else
col0 = 0;
}
}
}
// Step 2: Mark with 0 from (1,1) to (n-1, m-1):
for (int i = 1; i < n; i++) {
for (int j = 1; j < m; j++) {
if (matrix.get(i).get(j) != 0) {
// check for col & row:
if (matrix.get(i).get(0) == 0 || matrix.get(0).get(j) == 0) {
matrix.get(i).set(j, 0);
}
}
}
}
//step 3: Finally mark the 1st col & then 1st row:
if (matrix.get(0).get(0) == 0) {
for (int j = 0; j < m; j++) {
matrix.get(0).set(j, 0);
}
}
if (col0 == 0) {
for (int i = 0; i < n; i++) {
matrix.get(i).set(0, 0);
}
}
return matrix;
}
public static void main(String[] args) {
ArrayList<ArrayList<Integer>> matrix = new ArrayList<>();
matrix.add(new ArrayList<>(Arrays.asList(1, 1, 1)));
matrix.add(new ArrayList<>(Arrays.asList(1, 0, 1)));
matrix.add(new ArrayList<>(Arrays.asList(1, 1, 1)));
int n = matrix.size();
int m = matrix.get(0).size();
ArrayList<ArrayList<Integer>> ans = zeroMatrix(matrix, n, m);
System.out.println("The Final matrix is: ");
for (ArrayList<Integer> row : ans) {
for (Integer ele : row) {
System.out.print(ele + " ");
}
System.out.println();
}
}
}