Skip to main content

73.js

/** ------------------------------------------------------------------------------
*
* 73. Set Matrix Zeroes
* Topics: Matrix, Hash Table
* https://leetcode.com/problems/set-matrix-zeroes/description/?envType=daily-question&envId=2025-05-21
*
------------------------------------------------------------------------------ */
/**
* @param {number[][]} matrix
* @return {void} Do not return anything, modify matrix in-place instead.
*/
// var setZeroes = function (matrix) {
// const rowIndexOfZero = new Set();
// const colIndexOfZero = new Set();
// // iterate over matrix
// matrix.forEach((row, rowIdx) => {
// row.forEach((col, colIdx) => {
// if (matrix[rowIdx][colIdx] === 0) {
// rowIndexOfZero.add(rowIdx);
// colIndexOfZero.add(colIdx);
// }
// });
// });
// const rowLen = matrix.length;
// const colLen = matrix[0].length;

// for(let row=0; row<rowLen; row++){
// for(let col=0; col<colLen; col++){
// if(rowIndexOfZero.has(row) || colIndexOfZero.has(col)){
// matrix[row][col] = 0
// }
// }
// }
// };

var setZeroes = function (matrix) {
const rows = matrix.length - 1
const cols = matrix[0].length - 1

let isFirstRowZeroes = false

for (let r = 0; r <= rows; r++) {
for (let c = 0; c <= cols; c++) {
const value = matrix[r][c]

if (r === 0 && value === 0) {
isFirstRowZeroes = true
continue
}

if (value === 0) {
matrix[r][0] = 0
matrix[0][c] = 0
}
}
}

for (let r = 1; r <= rows; r++) {
const value = matrix[r][0]

if (value !== 0) continue

for (let c = 1; c <= cols; c++) {
matrix[r][c] = 0
}
}

for (let c = 0; c <= cols; c++) {
const value = matrix[0][c]

if (value !== 0) continue

for (let r = 1; r <= rows; r++) {
matrix[r][c] = 0
}
}

if (!isFirstRowZeroes) return

for (let c = 0; c <= cols; c++) {
matrix[0][c] = 0
}
}

console.log(
setZeroes([
[1, 1, 1],
[1, 0, 1],
[1, 1, 1],
]),
)