-
Notifications
You must be signed in to change notification settings - Fork 63
/
Copy pathSetMatrixZeroes.java
96 lines (69 loc) · 1.81 KB
/
SetMatrixZeroes.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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
/*
Source: https://leetcode.com/problems/set-matrix-zeroes/
Time: O(m * n), where m is the number of rows and n is the number of columns
Space: O(m * n), a boolean array is needed to seperate newly set zeros from the original ones
*/
class Solution {
public void setZeroes(int[][] matrix) {
int m = matrix.length;
int n = matrix[0].length;
boolean isVisited[][] = new boolean[m][n];
for(int i = 0; i < m; ++i) {
for(int j = 0; j < n; ++j) {
if(matrix[i][j] == 0 && !isVisited[i][j]) {
for(int k = 0; k < m; ++k) {
if(matrix[k][j] != 0) {
matrix[k][j] = 0;
isVisited[k][j] = true;
}
}
for(int k = 0; k < n; ++k) {
if(matrix[i][k] != 0) {
matrix[i][k] = 0;
isVisited[i][k] = true;
}
}
}
}
}
}
}
/*
Time: O(m * n), where m is the number of rows and n is the number of columns
Space: O(m + n), boolean arrays(rows and cols) are needed to mark it's row and column if it contains zeros
*/
class Solution {
public void setZeroes(int[][] matrix) {
int m = matrix.length;
int n = matrix[0].length;
boolean[] rows = new boolean[m];
boolean[] cols = new boolean[n];
// O(m * n)
for(int i = 0; i < m; ++i) {
for(int j = 0; j < n; ++j) {
if(matrix[i][j] == 0) {
rows[i] = true;
cols[j] = true;
}
}
}
// O(n * m)
// iterate columns
for(int i = 0; i < n; ++i) {
if(cols[i]) {
for(int j = 0; j < m; ++j) {
matrix[j][i] = 0;
}
}
}
// O(m * n)
// iterate rows
for(int i = 0; i < m; ++i) {
if(rows[i]) {
for(int j = 0; j < n; ++j) {
matrix[i][j] = 0;
}
}
}
}
}