python-leetcode-矩阵置零
73. 矩阵置零 - 力扣(LeetCode)
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])
row_zero = False # 记录是否需要将第一行全设为0
col_zero = False # 记录是否需要将第一列全设为0
# 第一次遍历,记录需要设为0的行和列
for i in range(m):
for j in range(n):
if matrix[i][j] == 0:
if i == 0:
row_zero = True
if j == 0:
col_zero = True
matrix[i][0] = 0 # 用第一列记录哪些行需要设为0
matrix[0][j] = 0 # 用第一行记录哪些列需要设为0
# 第二次遍历,根据记录将对应的行和列设为0
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
# 根据第一行和第一列的标记,处理第一行和第一列
if row_zero:
for j in range(n):
matrix[0][j] = 0
if col_zero:
for i in range(m):
matrix[i][0] = 0