var setZeroes = function(matrix) {
const m = matrix.length;
const n = matrix[0].length;
//用第一行第一列存放是否有0
//先判断第一行第一列是否有0
let oneRowhas0 = false;
let oneColhas0 = false;
for(let j = 0; j < n; j++)
if(matrix[0][j] == 0){
oneRowhas0 = true;
break;
}
for(let i = 0; i < m; i++)
if(matrix[i][0] == 0){
oneColhas0 = true;
break;
}
//遍历数组,若位置是0则在行列数组记录
for(let i = 1; i < m; i++)
for(let j = 1; j < n; j++)
if(matrix[i][j] == 0){
matrix[0][j] = 0;
matrix[i][0] = 0;
}
//遍历数组,查询该行该列是否有0,有的话置0
for(let i = 1; i < m; i++)
for(let j = 1; j < n; j++)
if(matrix[0][j] == 0|| matrix[i][0] == 0)
matrix[i][j] = 0;
//再将第一行第一列置0
if(oneRowhas0 == true)for(let j = 0; j < n; j++)matrix[0][j] = 0;
if(oneColhas0 == true)for(let i = 0; i < m; i++)matrix[i][0] = 0;
};
|