x 73. Set Matrix Zeroes
Last updated
Last updated
---> general solution
time: O(n x m)
space: O(1)
/**
* @param {number[][]} matrix
* @return {void} Do not return anything, modify matrix in-place instead.
*/
var setZeroes = function (matrix) {
let firstRowZero = false;
let firstColZero = false;
for (let i = 0; i < matrix.length; i++) {
for (let j = 0; j < matrix[0].length; j++) {
const curr = matrix[i][j];
if (curr !== 0) continue;
if (i === 0) firstRowZero = true;
if (j === 0) firstColZero = true;
matrix[i][0] = 0;
matrix[0][j] = 0;
}
}
for (let i = 1; i < matrix.length; i++) {
for (let j = 1; j < matrix[0].length; j++) {
if (matrix[i][0] === 0 || matrix[0][j] === 0) {
matrix[i][j] = 0;
}
}
}
if (firstRowZero) {
for (let col = 0; col < matrix[0].length; col++) {
matrix[0][col] = 0;
}
}
if (firstColZero) {
for (let row = 0; row < matrix.length; row++) {
matrix[row][0] = 0;
}
}
return matrix;
};
javascript solution
time: O(n^3)
space: O(1)
/**
* @param {number[][]} matrix
* @return {void} Do not return anything, modify matrix in-place instead.
*/
var setZeroes = function (matrix) {
for (let i = 0; i < matrix.length; i++) {
for (let j = 0; j < matrix[0].length; j++) {
const curr = matrix[i][j];
if (curr === 0) {
for (let row = 0; row < matrix.length; row++) {
matrix[row][j] !== 0 && (matrix[row][j] = undefined);
}
for (let col = 0; col < matrix[0].length; col++) {
matrix[i][col] !== 0 && (matrix[i][col] = undefined);
}
}
}
}
for (let i = 0; i < matrix.length; i++) {
for (let j = 0; j < matrix[0].length; j++) {
const curr = matrix[i][j];
if (curr === undefined) {
matrix[i][j] = 0;
}
}
}
return matrix;
};