Given an m x n matrix (a grid) of integers, modify the matrix in-place such that all elements in any row or column that contains a zero are set to zero.
The approach involves three steps:
function setZeroes(matrix) {
let m = matrix.length;
if (m === 0) return;
let n = matrix[0].length;
// Arrays to mark which rows and columns need to be set to zero
let zeroesRow = new Array(m).fill(false);
let zeroesCol = new Array(n).fill(false);
// Step 1: Identify rows and columns containing zeros
for (let i = 0; i < m; i++) {
for (let j = 0; j < n; j++) {
if (matrix[i][j] === 0) {
zeroesRow[i] = true;
zeroesCol[j] = true;
}
}
}
// Step 2: Set the entire row or column to zero
for (let i = 0; i < m; i++) {
if (zeroesRow[i]) {
matrix[i].fill(0);
}
}
for (let j = 0; j < n; j++) {
if (zeroesCol[j]) {
// Ensure all elements in this column are set to zero
for (let i = 0; i < m; i++) {
matrix[i][j] = 0;
}
}
}
return matrix;
}
zeroesRow and zeroesCol, respectively.fill(0). We then iterate through each marked column and set each element in that
column to zero.O(m + n), where m is the number of rows and n is the number of columns.zeroesRow and zeroesCol) to keep track of which rows and columns need to be zeroed out.Consider a 3x3 matrix:
1 2 0
4 5 6
7 8 9
0 0 0
4 5 6
7 8 9
0 0 0
4 5 0
7 8 0
https://leetcode.com/problems/set-matrix-zeroes/
Loading component...
Loading component...