把第一行和第一列当作标记;
循环内部元素,如果为0,则在对应的第一行和第一列进行标记;
二次循环内部元素,这次要反过来看,如果元素对应的第一行或者第一列为0,说明要置当前元素为0;
但在两次循环之前,要对第一行和第一列也进行标记,如果有0,则标记为true,在最后将第一行或者第一列都覆盖为0
java
class Solution {
public void setZeroes(int[][] matrix) {
int m = matrix.length;
int n = matrix[0].length;
boolean f1 = false;
boolean f2 = false;
for(int i = 0;i < n;i++){
if(matrix[0][i] == 0){
f1 = true;
}
}
for(int i = 0;i < m;i++){
if(matrix[i][0] == 0){
f2 = true;
}
}
for(int i = 1;i < m;i++){
for(int j = 1;j < n;j++){
if(matrix[i][j] == 0){
matrix[i][0] = matrix[0][j] = 0;
}
}
}
for(int i = 1;i < m;i++){
for(int j = 1;j < n;j++){
if(matrix[i][0] == 0 || matrix[0][j] == 0){
matrix[i][j] = 0;
}
}
}
if(f1){
for(int i = 0;i < n;i++){
matrix[0][i] = 0;
}
}
if(f2){
for(int i = 0;i < m;i++){
matrix[i][0] = 0;
}
}
}
}