Modify a matrix in place so that if any cell is 0, its entire row and column become 0.
Given an matrix, update it in place using the following rule: whenever a cell contains 0, every element in that cell’s row and every element in that cell’s column must also be set to 0.
The update should be based on the original positions of the zeroes, not on zeroes created during the process.
Input Format
- A 2D integer matrix
matrixwithmrows andncolumns. - Each cell contains an integer value.
Output Format
- Modify
matrixin place. - Return nothing in languages where in-place mutation is expected, or the updated matrix if your environment requires a return value.
Constraints
1 <= m, n- The matrix fits in memory.
- Aim for extra space if possible.
- The update must use the zero positions from the original matrix state.
Example 1
Input
matrix = [[1,1,1],[1,0,1],[1,1,1]]
Output
[[1,1,1],[0,0,0],[1,1,1]]
Explanation
The middle cell is zero, so its entire row and column become zero.
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]]
Explanation
The first row and the first and last columns contain a zero in the original matrix, so those rows and columns are cleared.
Premium problem context
Unlock deeper context for this problem
Premium adds guided hints, editorial links, similar variants, discussion resources, and concept maps so you can understand why a problem matters, not just solve it once.