Set Matrix Zeroes
You are given a matrix matrix of integers with m rows and n columns.
For every cell that holds 0 in the original matrix, set every cell in its row and every cell in its column to 0.
Return the changed matrix. You may change matrix and return it, or build a new one. Only the returned value is checked.
Note
Only zeros that are in the original matrix count. A cell that became 0 because of this rule does not clear its own row and column.
First find which rows and which columns must be cleared. Then write the zeros in a second pass. As an extra challenge, try to do it with O(1) extra space by using the first row and the first column as markers.
Examples
Example 1
- Input:
- [[5,1,7],[2,0,3],[4,6,8]]
- Output:
- [[5,0,7],[0,0,0],[4,0,8]]
The only zero is in row 1 and column 1, so that whole row and that whole column become 0.
Example 2
- Input:
- [[0,4,2,0],[3,5,1,6],[7,2,9,4]]
- Output:
- [[0,0,0,0],[0,5,1,0],[0,2,9,0]]
Row 0 has zeros in column 0 and column 3. Row 0 is cleared, and columns 0 and 3 are cleared.
Example 3
- Input:
- [[3,-2],[6,8]]
- Output:
- [[3,-2],[6,8]]
There is no zero, so nothing changes.
Constraints
1 <= m, n <= 6-9 <= matrix[i][j] <= 9
Run checks your code against the 3 examples. Submit checks it against all 303 tests and needs a free account. You can also try ideas in the free JavaScript or Python compiler.