73. Set Matrix Zeroes
Given an m x n integer matrix matrix, if an element is 0, set its entire row and column to 0's
ArrayExample 1:
- Input:
matrix = [[1,1,1],[1,0,1],[1,1,1]] - Output:
[[1,0,1],[0,0,0],[1,0,1]]
Example 2:
- Input:
matrix = [[0,1,2,0],[3,4,5,2],[1,3,1,5]] - Output:
[[0,0,0,0],[0,4,5,0],[0,3,1,0]]
Constraints:
m == matrix.lengthn == matrix[0].length1 <= m, n <= 200-2^31 <= matrix[i][j] <= 2^31 - 1- A straightforward solution using O(mn) space is probably a bad idea.
- A simple improvement uses O(m + n) space, but still not the best solution.
- Could you devise a constant space solution?
Approach
Solution
class Solution:
def setZeroes(self, matrix: List[List[int]]) -> None:
"""
Do not return anything, modify matrix in-place instead.
"""
m, n = len(matrix), len(matrix[0])
# 1. remember if row 0 or column 0 have their own zeros
row0_zero = any(matrix[0][c] == 0 for c in range(n))
col0_zero = any(matrix[r][0] == 0 for r in range(m))
# 2. use row 0 and column 0 as marker lists
for r in range(1, m):
for c in range(1, n):
if matrix[r][c] == 0:
matrix[r][0] = 0
matrix[0][c] = 0
# 3. zero the inner cells from the markers
for r in range(1, m):
for c in range(1, n):
if matrix[r][0] == 0 or matrix[0][c] == 0:
matrix[r][c] = 0
# 4. handle row 0 and column 0 last
if row0_zero:
for c in range(n):
matrix[0][c] = 0
if col0_zero:
for r in range(m):
matrix[r][0] = 0