编写一种算法,若M × N矩阵中某个元素为0,则将其所在的行与列清零。

示例 1:

1
2
3
4
5
6
7
8
9
10
11
12
输入:
[
[1,1,1],
[1,0,1],
[1,1,1]
]
输出:
[
[1,0,1],
[0,0,0],
[1,0,1]
]

示例 2:

1
2
3
4
5
6
7
8
9
10
11
12
输入:
[
[0,1,2,0],
[3,4,5,2],
[1,3,1,5]
]
输出:
[
[0,0,0,0],
[0,4,5,0],
[0,3,1,0]
]
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
public void setZeroes(int[][] matrix) {

int rowLength = matrix.length;
int colLength = matrix[0].length;
int[] rowIndex = new int[rowLength];
int[] colIndex = new int[colLength];

for (int i = 0; i < rowLength; i++) {
for (int j = 0; j < colLength; j++) {
if (matrix[i][j] == 0){
rowIndex[i] = 1;
colIndex[j] = 1;
}
}
}

for (int i = 0; i < rowLength; i++) {
for (int j = 0; j < colLength; j++) {
if (rowIndex[i] == 1 || colIndex[j] == 1){
matrix[i][j] = 0;
}
}
}

}

作者:力扣 (LeetCode)
链接:https://leetcode.cn/leetbook/read/array-and-string/ciekh/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。