-
Notifications
You must be signed in to change notification settings - Fork 12
Expand file tree
/
Copy pathSetMatrixToZero.java
More file actions
66 lines (58 loc) · 2.14 KB
/
SetMatrixToZero.java
File metadata and controls
66 lines (58 loc) · 2.14 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
import java.util.*;
public class SetMatrixToZero {
static void setZeroes(int[][] matrix) {
int rows = matrix.length, cols = matrix[0].length;
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
if (matrix[i][j] == 0) {
int ind = i - 1;
while (ind >= 0) {
if (matrix[ind][j] != 0) {
matrix[ind][j] = -1;
}
ind--;
}
ind = i + 1;
while (ind < rows) {
if (matrix[ind][j] != 0) {
matrix[ind][j] = -1;
}
ind++;
}
ind = j - 1;
while (ind >= 0) {
if (matrix[i][ind] != 0) {
matrix[i][ind] = -1;
}
ind--;
}
ind = j + 1;
while (ind < cols) {
if (matrix[i][ind] != 0) {
matrix[i][ind] = -1;
}
ind++;
}
}
}
}
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
if (matrix[i][j] <= 0) {
matrix[i][j] = 0;
}
}
}
}
public static void main(String args[]) {
int arr[][] = {{0, 1, 2, 0}, {3, 4, 5, 2}, {1, 3, 1, 5}};
setZeroes(arr);
System.out.println("The Final Matrix is ");
for (int i = 0; i < arr.length; i++) {
for (int j = 0; j < arr[0].length; j++) {
System.out.print(arr[i][j] + " ");
}
System.out.println();
}
}
}