-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathLeetCode-73-Set-Matrix-Zeroes.java
More file actions
97 lines (86 loc) · 2.7 KB
/
LeetCode-73-Set-Matrix-Zeroes.java
File metadata and controls
97 lines (86 loc) · 2.7 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
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
97
/*
LeetCode: https://leetcode.com/problems/set-matrix-zeroes/
LintCode: http://www.lintcode.com/problem/set-matrix-zeroes/
JiuZhang: http://www.jiuzhang.com/solutions/set-matrix-zeroes/
ProgramCreek: http://www.programcreek.com/2012/12/leetcode-set-matrix-zeroes-java/
Analysis:
*/
public class Solution {
// 1.
public void setZeroes(int[][] matrix) {
boolean firstRowZeroes = false;
boolean firstColumnZeroes = false;
// set first row and column zero or not
for(int i = 0; i < matrix[0].length; i++){
if(matrix[0][i] == 0){
firstRowZeroes = true;
break;
}
}
for(int j = 0; j < matrix.length; j++){
if(matrix[j][0] == 0){
firstColumnZeroes = true;
break;
}
}
// mark zeroes on 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;
}
}
}
// use mark to set elements
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 first row and column
if(firstRowZeroes){
for(int i = 0; i < matrix[0].length; i++){
matrix[0][i] = 0;
}
}
if(firstColumnZeroes){
for(int i = 0; i < matrix.length; i++){
matrix[i][0] = 0;
}
}
}
// 2.
public void setZeroes(int[][] matrix) {
boolean fr = false,fc = false;
for(int i = 0; i < matrix.length; i++) {
for(int j = 0; j < matrix[0].length; j++) {
if(matrix[i][j] == 0) {
if(i == 0) fr = true;
if(j == 0) fc = true;
matrix[0][j] = 0;
matrix[i][0] = 0;
}
}
}
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;
}
}
}
if(fr) {
for(int j = 0; j < matrix[0].length; j++) {
matrix[0][j] = 0;
}
}
if(fc) {
for(int i = 0; i < matrix.length; i++) {
matrix[i][0] = 0;
}
}
}
}