-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMatrix.java
More file actions
58 lines (50 loc) · 1.39 KB
/
Matrix.java
File metadata and controls
58 lines (50 loc) · 1.39 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
import java.util.HashSet;
import java.util.Set;
class Matrix {
public void setZeroes(int[][] matrix) {
Set<Integer> r = new HashSet<>();
Set<Integer> c = new HashSet<>();
int rows = matrix.length;
int cols = matrix[0].length;
// Finding rows and columns with 0 values
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
if (matrix[i][j] == 0) {
r.add(i);
c.add(j);
}
}
}
// Now set rows to 0
for (int i : r) {
for (int j = 0; j < cols; j++) {
matrix[i][j] = 0;
}
}
// Now set columns to 0
for (int j : c) {
for (int i = 0; i < rows; i++) {
matrix[i][j] = 0;
}
}
}
public static void main(String[] args)
{
int[][] matrix = {
{1, 0, 3},
{4, 0, 6},
{7, 8, 9}
};
// Create a Solution object
Matrix solution = new Matrix();
// Call the setZeroes method to modify the matrix
solution.setZeroes(matrix);
// Print the modified matrix
for (int[] row : matrix) {
for (int num : row) {
System.out.print(num + " ");
}
System.out.println();
}
}
}