-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathSetMatrixZeroes.java
More file actions
105 lines (84 loc) · 1.91 KB
/
SetMatrixZeroes.java
File metadata and controls
105 lines (84 loc) · 1.91 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
package array_and_matrix;
/**
* @Author: Wenhang Chen
* @Description:给定一个 m x n 的矩阵,如果一个元素为 0,则将其所在行和列的所有元素都设为 0。请使用原地算法。
* <p>
* 示例 1:
* <p>
* 输入:
* [
* [1,1,1],
* [1,0,1],
* [1,1,1]
* ]
* 输出:
* [
* [1,0,1],
* [0,0,0],
* [1,0,1]
* ]
* 示例 2:
* <p>
* 输入:
* [
* [0,1,2,0],
* [3,4,5,2],
* [1,3,1,5]
* ]
* 输出:
* [
* [0,0,0,0],
* [0,4,5,0],
* [0,3,1,0]
* ]
* @Date: Created in 9:00 1/26/2020
* @Modified by:
*/
class Solution {
public void setZeroes(int[][] matrix) {
int row = matrix.length;
int col = matrix[0].length;
boolean row0_flag = false;
boolean col0_flag = false;
// 第一行是否有零
for (int j = 0; j < col; j++) {
if (matrix[0][j] == 0) {
row0_flag = true;
break;
}
}
// 第一列是否有零
for (int i = 0; i < row; i++) {
if (matrix[i][0] == 0) {
col0_flag = true;
break;
}
}
// 把第一行第一列作为标志位
for (int i = 1; i < row; i++) {
for (int j = 1; j < col; j++) {
if (matrix[i][j] == 0) {
matrix[i][0] = matrix[0][j] = 0;
}
}
}
// 置0
for (int i = 1; i < row; i++) {
for (int j = 1; j < col; j++) {
if (matrix[i][0] == 0 || matrix[0][j] == 0) {
matrix[i][j] = 0;
}
}
}
if (row0_flag) {
for (int j = 0; j < col; j++) {
matrix[0][j] = 0;
}
}
if (col0_flag) {
for (int i = 0; i < row; i++) {
matrix[i][0] = 0;
}
}
}
}