Menu
CoddyTech

Set Matrix Zeroes

The input is an m × n grid of integers, given row by row, so matrix[i][j] sits in row i and column j. Wherever the grid holds a 0, set that whole row and that whole column to 0. Only the zeros present at the start count: a cell you turn into 0 does not clear its own row or column. You may change the grid in place; return it.

Function

setZeroes(matrix: integer-2d-array) → integer-2d-array
matrixinteger-2d-array
the grid of integers, one inner list per row
Returnsinteger-2d-array
the matrix with every row and every column that held a 0 set to 0

Constraints

  • m == matrix.length and n == matrix[i].length
  • 1 ≤ m, n ≤ 1000 and m × n ≤ 5000
  • All m rows hold n values.
  • -1000 ≤ matrix[i][j] ≤ 1000

Examples

Input
matrix = [[3, 8, 1], [5, 0, 7], [2, 6, 4]]
Output
[[3, 0, 1], [0, 0, 0], [2, 0, 4]]
Explanation
The only 0 sits in row 1, column 1. Row 1 becomes all zeros, and so does column 1, which turns the 8 and the 6 into 0. The four corners are in neither line and keep their values.
challenge icon

Follow-up

The best approach below keeps two extra booleans. Can you make do with one, letting matrix[0][0] stand for the first row?

Reset code
def setZeroes(matrix):
    # Write code here

Test #1

Test #2

Argument

matrix = [[3, 8, 1], [5, 0, 7], [2, 6, 4]]

Expected Output

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