Zero Out Rows and Columns Containing a Zero

Implement setMatrixZeroes

Given a matrix, if any cell contains 0, set its entire row and entire column to 0 — based on the ORIGINAL zero positions, not any zeros created along the way. The naive fix is to copy the matrix first so the original zero positions stay available while zeroing happens. But that copy costs O(rows·cols) extra space. The clever trick: the matrix's own first row and first column can double as marker storage for which rows/columns need zeroing — no extra structure needed, just two booleans to remember whether the first row/column themselves originally had a zero before they get repurposed.

Example 1:

Input: matrix = [[1,1,1],[1,0,1],[1,1,1]]

Output: [[1,0,1],[0,0,0],[1,0,1]]

Example 2:

Input: matrix = [[0,1,2,0],[3,4,5,2],[1,3,1,5]]

Output: [[0,0,0,0],[0,4,5,0],[0,3,1,0]]

Example 3:

Input: matrix = [[1,2],[3,4]]

Output: [[1,2],[3,4]]

+ 7 hidden test cases run on Submit.

Constraints:

  • 1 ≤ rows, cols ≤ 20
  • -100 ≤ matrix[i][j] ≤ 100

matrix =

[[1,1,1], [1,0,1], [1,1,1]]