Set Matrix Zeroes
MediumMath & Geometry
You are given an m x n integer matrix. For every cell that is 0 in the original matrix, set every cell in its row and every cell in its column to 0. Return the resulting matrix.
Only zeroes that were present at the start trigger clearing; cells that become 0 during the process do not cause any further rows or columns to be cleared.
Try to modify matrix in place and return it. Returning a newly built matrix is also accepted by the tests.
Follow-up: an O(m + n) extra-space solution is straightforward. Can you do it with O(1) extra space?
Example 1
- Input:
- matrix = [[1,0,3],[4,5,6],[0,8,9]]
- Output:
- [[0,0,0],[0,0,6],[0,0,0]]
- Explanation
- The zero at (0,1) clears row 0 and column 1; the zero at (2,0) clears row 2 and column 0. Only the 6 at (1,2) is in neither, so it survives. Zeroes written along the way do not clear anything further.
Example 2
- Input:
- matrix = [[5,6,7],[8,9,4]]
- Output:
- [[5,6,7],[8,9,4]]
- Explanation
- Nothing is zero, so the matrix is returned unchanged.
Example 3
- Input:
- matrix = [[1],[0],[3]]
- Output:
- [[0],[0],[0]]
- Explanation
- The zero clears its row and its column, and the column is the whole matrix.
Constraints
m == matrix.length,n == matrix[0].length1 <= m, n <= 200-2^31 <= matrix[i][j] <= 2^31 - 1