-
Notifications
You must be signed in to change notification settings - Fork 0
/
Set Matrix Zeroes (Constant Space)
53 lines (47 loc) · 1.39 KB
/
Set Matrix Zeroes (Constant Space)
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
public void setZeroes(int[][] matrix) {
int rownum = matrix.length;
if (rownum == 0) return;
int colnum = matrix[0].length;
if (colnum == 0) return;
boolean hasZeroFirstRow = false, hasZeroFirstColumn = false;
// Does first row have zero?
for (int j = 0; j < colnum; ++j) {
if (matrix[0][j] == 0) {
hasZeroFirstRow = true;
break;
}
}
// Does first column have zero?
for (int i = 0; i < rownum; ++i) {
if (matrix[i][0] == 0) {
hasZeroFirstColumn = true;
break;
}
}
// find zeroes and store the info in first row and column
for (int i = 1; i < matrix.length; ++i) {
for (int j = 1; j < matrix[0].length; ++j) {
if (matrix[i][j] == 0) {
matrix[i][0] = 0;
matrix[0][j] = 0;
}
}
}
// set zeroes except the first row and column
for (int i = 1; i < matrix.length; ++i) {
for (int j = 1; j < matrix[0].length; ++j) {
if (matrix[i][0] == 0 || matrix[0][j] == 0) matrix[i][j] = 0;
}
}
// set zeroes for first row and column if needed
if (hasZeroFirstRow) {
for (int j = 0; j < colnum; ++j) {
matrix[0][j] = 0;
}
}
if (hasZeroFirstColumn) {
for (int i = 0; i < rownum; ++i) {
matrix[i][0] = 0;
}
}
}