
[LeetCode] 73. Set Matrix Zeroes


zero_rows, zero_colsmatrix[i][j] = 0 if i in zero_rows or j in zero_colsclass Solution:
def setZeroes(self, matrix: List[List[int]]) -> None:
m, n = len(matrix), len(matrix[0])
zero_rows, zero_cols = set(), set()
# 1) record which rows/cols must be zero
for i in range(m):
for j in range(n):
if matrix[i][j] == 0:
zero_rows.add(i)
zero_cols.add(j)
# 2) apply
for i in range(m):
for j in range(n):
if i in zero_rows or j in zero_cols:
matrix[i][j] = 0
We can achieve O(1) extra space by using the matrix itself as a marker board:
firstRowZero: whether row 0 originally has a zerofirstColZero: whether col 0 originally has a zerofirstRowZero, firstColZero(i, j) (excluding first row/col), if it is 0, mark:matrix[i][0] = 0 (row marker)matrix[0][j] = 0 (col marker)(i, j), set it to 0 if its row or column is markedfirstRowZero / firstColZero is trueclass Solution:
def setZeroes(self, matrix: List[List[int]]) -> None:
m, n = len(matrix), len(matrix[0])
# 1) check whether first row / first col originally contain zero
firstRowZero = any(matrix[0][j] == 0 for j in range(n))
firstColZero = any(matrix[i][0] == 0 for i in range(m))
# 2) use first row/col as markers
for i in range(1, m):
for j in range(1, n):
if matrix[i][j] == 0:
matrix[i][0] = 0
matrix[0][j] = 0
# 3) apply markers to inner cells
for i in range(1, m):
for j in range(1, n):
if matrix[i][0] == 0 or matrix[0][j] == 0:
matrix[i][j] = 0
# 4) zero out first row/col if needed
if firstRowZero:
for j in range(n):
matrix[0][j] = 0
if firstColZero:
for i in range(m):
matrix[i][0] = 0