面试题 01.08. 零矩阵
题目描述
编写一种算法,若M × N矩阵中某个元素为0,则将其所在的行与列清零。
示例 1:
输入:
[
[1,1,1],
[1,0,1],
[1,1,1]
]
输出:
[
[1,0,1],
[0,0,0],
[1,0,1]
]
示例 2:
输入:
[
[0,1,2,0],
[3,4,5,2],
[1,3,1,5]
]
输出:
[
[0,0,0,0],
[0,4,5,0],
[0,3,1,0]
]
解答
var setZeroes = function(matrix) {
let helper = JSON.parse(JSON.stringify(matrix));
for (let i = 0; i < helper.length; ++i) {
for (let j = 0; j < helper[0].length; ++j) {
if (!helper[i][j]) {
for (let k = 0; k < helper.length; ++k) matrix[k][j] = 0;
for (let k = 0; k < helper[0].length; ++k) matrix[i][k] = 0;
}
}
}
for (let i = 0; i < matrix.length; ++i) {
for (let j = 0; j < matrix[0].length; ++j) {
if (matrix[i][j] === 0) {
for (let k = 0; k < matrix.length; ++k) if ( matrix[k][j] !== 0) matrix[k][j] = NaN;
for (let k = 0; k < matrix[0].length; ++k) if ( matrix[i][k] !== 0) matrix[i][k] = NaN;
}
}
}
for (let i = 0; i < matrix.length; ++i) {
for (let j = 0; j < matrix[0].length; ++j) {
if (isNaN(matrix[i][j])) matrix[i][j] = 0;
}
}
const m = matrix.length, n = matrix[0].length;
const rowFlag = new Array(m).fill(false);
const colFlag = new Array(n).fill(false);
for (let i = 0; i < m; ++i) {
for (let j = 0; j < n; ++j) {
if (matrix[i][j] === 0) {
rowFlag[i] = true;
colFlag[j] = true;
}
}
}
for (let i = 0; i < m; ++i) {
for (let j = 0; j < n; ++j) {
if(rowFlag[i] || colFlag[j]) matrix[i][j] = 0;
}
}
};