forked from chuyi2007/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSetMatrixZeroes.java
More file actions
42 lines (42 loc) · 1.31 KB
/
SetMatrixZeroes.java
File metadata and controls
42 lines (42 loc) · 1.31 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
//O(M*N)
public class Solution {
public void setZeroes(int[][] matrix) {
// Start typing your Java solution below
// DO NOT write main() function
int m = matrix.length, n = matrix[0].length;
int row = -1, col = -1;
for(int i = 0; i < m; ++i)
for(int j = 0; j < n; ++j)
if(matrix[i][j] == 0){
row = i;
col = j;
i = m;
j = n;
}
//not found
if(row == -1)
return;
//set row and col as zero flags
for(int i = 0; i < m; ++i)
for(int j = 0; j < n; ++j)
if(matrix[i][j] == 0){
matrix[row][j] = 0;
matrix[i][col] = 0;
}
//zeroes of matrix
for(int i = 0; i < m; ++i)
if(i != row && matrix[i][col] == 0){
for(int j = 0; j < n; ++j)
matrix[i][j] = 0;
}
for(int j = 0; j < n; ++j)
if(j != col && matrix[row][j] == 0){
for(int i = 0; i < m; ++i)
matrix[i][j] = 0;
}
for(int i = 0; i < m; ++i)
matrix[i][col] = 0;
for(int j = 0; j < n; ++j)
matrix[row][j] = 0;
}
}