v9.1.1
Menu

Set Matrix Zeroes

mediumFREEMath & GeometryBlind 75

Given an m x n matrix, if an element is 0, set its entire row and column to 0. Do it in-place.

Only zeros present in the original matrix trigger zeroing; zeros you write along the way do not. The function modifies matrix in place and returns nothing; the tests then print its rows, space-separated.

Example

Input
1,1,1
1,0,1
1,1,1
Output
1 0 1
0 0 0
1 0 1
Reasoning
  • Input: matrix is a 3×33 \times 3 grid of integers, all 1s except a single 0 at row 1, column 1 (counting from 0).
  • Which lines get wiped: each original zero at position (r,c)(r, c) condemns all of row rr and all of column cc. Here the set of zero rows is R={1}R = \{1\} and of zero columns C={1}C = \{1\}.
  • Rule per cell: entry (i,j)(i, j) becomes 0 if i∈Ri \in R or j∈Cj \in C, otherwise it keeps its value. Row 1 becomes 0 0 0; column 1 zeroes the middle entry of rows 0 and 2; the four corners keep their 1s.
  • Output: the same grid, changed in place, printed row by row as 1 0 1, 0 0 0, 1 0 1.
  • Notice that RR and CC come only from zeros present before any change. The new zeros in row 1 must not spread further, or the whole grid would collapse to 0. A grid with no zeros comes back untouched.

Constraints

  • 1 <= m, n <= 200
  • -2^31 <= matrix[i][j] <= 2^31 - 1

More from Blind 75

solution.py

Test results

Sign in to run your code against the test cases.