AceYourInterviews
Checking sign-in…

9. Set Matrix Zeroes

IntermediateIn-place row and column markers

Look at the zeros present in the original matrix. Every row and column containing one of those original zeros must become entirely zero, while unrelated cells retain their values.

A zero written during the update must not create a new requirement to zero additional rows or columns. Preserve the original matrix and row objects.

Example 1

Input

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

Output

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

Explanation: Only the middle original row and column are zeroed; the four corners remain one.

Example 2

Input

[[0,1],[2,3]]

Output

[[0,0],[0,3]]

Explanation: An original top-left zero affects the first row and first column, not the entire matrix.

Constraints

  • 0 <= matrix.length <= 100
  • 0 <= matrix[r].length <= 100
  • -231 <= matrix[r][c] <= 231 - 1
  • The matrix is rectangular and all rows are non-null.
Hints
Hint 1

What information about the original zero positions must survive mutation?

Hint 2

Separate row flags from column flags.

Hint 3

Use first-row/column markers, preserve their original zero flags, and clear the boundaries last.

Practice on LeetCode ↗
Code
Saved on this deviceLn 1, Col 1

An interior zero must not erase corners

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