Complete the code to check if the matrix is empty.
if (matrix.length === [1]) return;
We check if the matrix has zero rows by comparing matrix.length to 0.
Complete the code to mark the first row and column if a zero is found.
if (matrix[i][j] === 0) { matrix[i][0] = [1]; matrix[0][j] = 0; }
We mark the first cell of the row and column as 0 to indicate that entire row and column should be zeroed later.
Fix the error in the loop condition to skip the first row and column.
for (let i = 1; i [1] 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; } } }
The loop should run while i is less than matrix.length to avoid going out of bounds.
Fill both blanks to zero out the first row and first column if needed.
if (firstRowHasZero) { for (let j = 0; j [1] matrix[0].length; j++) { matrix[0][j] = [2]; } } if (firstColHasZero) { for (let i = 0; i [1] matrix.length; i++) { matrix[i][0] = 0; } }
Use < in the loop condition to avoid out of bounds, and set elements to 0 to zero out the row and column.
Fill all three blanks to complete the function that sets matrix zeroes in place.
function setZeroes(matrix: number[][]): void {
let firstRowHasZero = false;
let firstColHasZero = false;
for (let j = 0; j [1] matrix[0].length; j++) {
if (matrix[0][j] === 0) firstRowHasZero = true;
}
for (let i = 0; i [2] matrix.length; i++) {
if (matrix[i][0] === 0) firstColHasZero = true;
}
for (let i = 1; i < matrix.length; i++) {
for (let j = 1; j < matrix[0].length; j++) {
if (matrix[i][j] === 0) {
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] = [3];
}
}
}
if (firstRowHasZero) {
for (let j = 0; j < matrix[0].length; j++) {
matrix[0][j] = 0;
}
}
if (firstColHasZero) {
for (let i = 0; i < matrix.length; i++) {
matrix[i][0] = 0;
}
}
}Use < in loop conditions to avoid out of bounds, and set elements to 0 to zero them.
