All problems

Set Matrix Zeroes

Medium · matrix

You are given a grid of integers matrix with m rows and n columns. Wherever the grid holds a 0, wipe out the whole row and the whole column that cell belongs to: every cell in them becomes 0.

Only the zeros that were in the grid you were given count. Zeros created by the wiping do not wipe anything further. A grid without any zero is returned unchanged.

Return the resulting grid.

Examples

Example 1

Input: matrix = [[1, 1, 1], [1, 0, 1], [1, 1, 1]]

Output: [[1, 0, 1], [0, 0, 0], [1, 0, 1]]

The only zero is in the middle, so the middle row and the middle column become 0.

Example 2

Input: matrix = [[0, 2, 3, 4], [5, 6, 0, 8], [9, 10, 11, 12]]

Output: [[0, 0, 0, 0], [0, 0, 0, 0], [0, 10, 0, 12]]

Zeros at row 0, column 0 and row 1, column 2 wipe rows 0 and 1 and columns 0 and 2.

Example 3

Input: matrix = [[3, 4], [5, 6]]

Output: [[3, 4], [5, 6]]

There is no zero, so nothing changes.

Constraints