Set Matrix Zeroes
Examples
Example 1:
Input: matrix = [
[0,1],
[1,0]
]
Output: [
[0,0],
[0,0]
]
Example 2:
Input: matrix = [
[1,2,3],
[4,0,5],
[6,7,8]
]
Output: [
[1,0,3],
[0,0,0],
[6,0,8]
]
Example 1:
Input: matrix = [
[0,1],
[1,0]
]
Output: [
[0,0],
[0,0]
]
Example 2:
Input: matrix = [
[1,2,3],
[4,0,5],
[6,7,8]
]
Output: [
[1,0,3],
[0,0,0],
[6,0,8]
]
Given an m x n matrix of integers matrix, if an element is 0, set its entire row and column to 0's.
You must update the matrix in-place.
Follow up: Could you solve it using O(1) space?
1 <= matrix.length, matrix[0].length <= 100-2^31 <= matrix[i][j] <= (2^31) - 1Use the first row and first column as markers. First, record whether the first row or column should be zeroed. Then, for every zero cell, mark its row and column in the first row/column. Finally, zero out rows/columns based on these markers and handle the first row/column.
The marker cells indicate which rows and columns must be zeroed without extra space. A zero in any cell correctly propagates to its row and column, and the initial flags preserve the original state of the first row/column.
O(m * n)O(1)class Solution:
def setZeroes(self, matrix: List[List[int]]) -> None:
rows, cols = len(matrix), len(matrix[0])
first_row_zero = any(matrix[0][c] == 0 for c in range(cols))
first_col_zero = any(matrix[r][0] == 0 for r in range(rows))
for r in range(1, rows):
for c in range(1, cols):
if matrix[r][c] == 0:
matrix[r][0] = 0
matrix[0][c] = 0
for r in range(1, rows):
if matrix[r][0] == 0:
for c in range(1, cols):
matrix[r][c] = 0
for c in range(1, cols):
if matrix[0][c] == 0:
for r in range(1, rows):
matrix[r][c] = 0
if first_row_zero:
for c in range(cols):
matrix[0][c] = 0
if first_col_zero:
for r in range(rows):
matrix[r][0] = 0