题目
编写一种算法,若M × N矩阵中某个元素为0,则将其所在的行与列清零。
示例
输入:
[
[1,1,1],
[1,0,1],
[1,1,1]
]
输出:
[
[1,0,1],
[0,0,0],
[1,0,1]
]
输入:
[
[0,1,2,0],
[3,4,5,2],
[1,3,1,5]
]
输出:
[
[0,0,0,0],
[0,4,5,0],
[0,3,1,0]
]
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/zero-matrix-lcci
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
方法1:模拟
Java实现
class Solution {
public void setZeroes(int[][] matrix) {
int m = matrix.length, n = matrix[0].length;
List<Integer> row = new ArrayList<>();
List<Integer> col = new ArrayList<>();
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (matrix[i][j] == 0) {
if (!row.contains(i)) row.add(i);
if (!col.contains(j)) col.add(j);
}
}
}
//每行令为0
for (int i = 0; i < row.size(); i++) {
for (int j = 0; j < n; j++) {
matrix[row.get(i)][j] = 0;
}
}
//每列令为0
for (int i = 0; i < col.size(); i++) {
for (int j = 0; j < m; j++) {
matrix[j][col.get(i)] = 0;
}
}
}
}