LeetCode 73. 矩阵置零python3
原题链接
中等
作者:
xanxus1111
,
2020-07-16 15:30:27
,
所有人可见
,
阅读 584
class Solution:
def setZeroes(self, matrix: List[List[int]]) -> None:
"""
Do not return anything, modify matrix in-place instead.
"""
if not len(matrix) or not len(matrix[0]): return
n, m = len(matrix), len(matrix[0])
r0, c0 = 1, 1
#遍历第一列是否有0
for i in range(n):
if not matrix[i][0]: c0 = 0
#遍历第一行是否有0
for i in range(m):
if not matrix[0][i]: r0 = 0
#检查每一列是否有0用第一列记录
for j in range(1,m):
for i in range(n):
if not matrix[i][j]: matrix[0][j] = 0
#检查每一行是否有0用第一行记录
for i in range(1,n):
for j in range(m):
if not matrix[i][j]: matrix[i][0] = 0
#如果第j列有0,那么这一列所有数=0
for j in range(1, m):
if not matrix[0][j]:
for i in range(n):
matrix[i][j] = 0
#如果第i行有0,那么这一行所有数=0
for i in range(1,n):
if not matrix[i][0]:
for j in range(m):
matrix[i][j] = 0
#如果r0是0,那么第一行所有数=0
if not r0:
for j in range(m): matrix[0][j] = 0
#如果c0是0,那么第一列所有数 = 0
if not c0:
for i in range(n): matrix[i][0] = 0