题目
给定一个 m x n 的矩阵,如果一个元素为 0 ,则将其所在行和列的所有元素都设为 0 。请使用 原地 算法。
示例 1:
输入:matrix = [[1,1,1],[1,0,1],[1,1,1]]
输出:[[1,0,1],[0,0,0],[1,0,1]]
示例 2:
输入:matrix = [[0,1,2,0],[3,4,5,2],[1,3,1,5]]
输出:[[0,0,0,0],[0,4,5,0],[0,3,1,0]]
提示:
m==matrix.length
n == matrix[0].length
1 <= m, n <= 200
-231 <= matrix[i][j] <= 231 - 1
代码
package leetcodeday1;
public class leetcode73 {
// 标记数组,将矩阵中元素为0的行和列标记出来
// 如果该元素在元素为0的行或列上,将其置0
public void setZeroes(int[][] matrix) {
int[] row = new int[matrix.length];
int[] col = new int[matrix[0].length];
for (int i = 0; i < matrix.length; i++){
for (int j = 0; j < matrix[i].length; j++){
if (matrix[i][j] == 0){
row[i] = 1;
col[j] = 1;
}
}
}
for (int i = 0; i < matrix.length; i++){
for (int j = 0; j < matrix[i].length; j++){
if (row[i] == 1 || col[j] == 1){
matrix[i][j] = 0;
}
}
}
}
public static void main(String[] args) {
leetcode73 obj = new leetcode73();
int[][] matrix = {
{0, 1, 2, 0},{3, 4, 5, 2},{1, 3, 1, 5}
};
obj.setZeroes(matrix);
}
}