Set Matrix Zeroes in TypeScript

function setZeroes(matrix: number[][]): void {
  const m = matrix.length; // Number of rows
  const n = matrix[0].length; // Number of columns
  let firstRow = false; // Flag to indicate if the first row needs to be set to 0
  let firstCol = false; // Flag to indicate if the first column needs to be set to 0

  // Check if the first row contains any zeros
  for (let j = 0; j < n; j++) {
    if (matrix[0][j] === 0) {
      firstRow = true;
      break;
    }
  }

  // Check if the first column contains any zeros
  for (let i = 0; i < m; i++) {
    if (matrix[i][0] === 0) {
      firstCol = true;
      break;
    }
  }

  // Use the first row and first column to mark the rows and columns to be set to zero
  for (let i = 1; i < m; i++) {
    for (let j = 1; j < n; j++) {
      if (matrix[i][j] === 0) {
        matrix[i][0] = 0; // Mark the corresponding element in the first column
        matrix[0][j] = 0; // Mark the corresponding element in the first row
      }
    }
  }

  // Set the marked rows and columns to zero (excluding the first row and first column)
  for (let i = 1; i < m; i++) {
    for (let j = 1; j < n; j++) {
      if (matrix[i][0] === 0 || matrix[0][j] === 0) {
        matrix[i][j] = 0;
      }
    }
  }

  // Set the first row to zero if necessary
  if (firstRow) {
    for (let j = 0; j < n; j++) {
      matrix[0][j] = 0;
    }
  }

  // Set the first column to zero if necessary
  if (firstCol) {
    for (let i = 0; i < m; i++) {
      matrix[i][0] = 0;
    }
  }
}

PrevNext