-
Notifications
You must be signed in to change notification settings - Fork 0
/
SetZeroMatrix.java
81 lines (75 loc) · 2.43 KB
/
SetZeroMatrix.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
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
80
81
import java.util.ArrayList;
import java.util.List;
class SetZeroMatrix {
public static void main(String[] args) {
int[][] matrix = {{1,1,1},{1,0,1},{1,1,1}};
int[][] matrix1 ={{0,1,2,0},{3,4,5,2},{1,3,1,5}};
setZeroes(matrix1);
}
public static void setZeroes(int[][] matrix) {
// Lists to store the indices of rows and columns containing zero elements
List<Integer> row = new ArrayList<>();
List<Integer> col = new ArrayList();
// Iterate through the matrix to find the zero elements and store their indices
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[i].length; j++) {
if (matrix[i][j] == 0) {
row.add(i);
col.add(j);
}
}
}
// Iterate through the matrix again and set elements in rows and columns with zero elements to zero
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[i].length; j++) {
if (row.contains(i) || col.contains(j)) {
matrix[i][j] = 0;
}
}
}
// The function returns void (no specific return value is needed)
return;
}
public static void setZeroesWorst(int[][] matrix) {
int m = matrix.length;
int n = matrix[0].length;
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (matrix[i][j] == 0) {
matrix[0][j] = -99999;
matrix[i][0] = -99999;
}
}
}
for(int i=0;i<m;i++){
if(matrix[i][0]==-99999){
for(int k=0;k<n;k++){
if(matrix[i][k]!=-99999){
matrix[i][k]=0;
}
}
// matrix[i][0]=0;
}
}
for(int i=0;i<n;i++){
if(matrix[0][i]==-99999){
for(int k=0;k<m;k++){
if(matrix[k][i]!=-99999){
matrix[k][i]=0;
}
}
// matrix[0][i]=0;
}
}
for(int i=0;i<m;i++){
if(matrix[i][0]==-99999){
matrix[i][0]=0;
}
}
for(int i=0;i<n;i++){
if(matrix[0][i]==-99999){
matrix[0][i]=0;
}
}
}
}