function zeroMatrix(matrix) {
let rowHasZero = false;
let colHasZero = false;
for (let j = 0; j < matrix[0].length; j++) {
if (matrix[0][j] === 0) {
rowHasZero = true;
break;
}
}
for (let i = 0; i < matrix.length; i++) {
if (matrix[i][0] === 0) {
colHasZero = true;
break;
}
}
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++) {
if (matrix[i][0] === 0) {
nullifyRow(matrix, i);
}
}
for (let j = 1; j < matrix[0].length; j++) {
if (matrix[0][j] === 0) {
nullifyColumn(matrix, j);
}
}
if (rowHasZero) {
nullifyRow(matrix, 0);
}
if (colHasZero) {
nullifyColumn(matrix, 0);
}
return matrix;
}
function nullifyRow(matrix, i) {
for (let j = 0; j < matrix[0].length; j++) {
matrix[i][j] = 0;
}
}
function nullifyColumn(matrix, j) {
for (let i = 0; i < matrix.length; i++) {
matrix[i][j] = 0;
}
}