1、题目描述
给定一个 m x n 的矩阵,如果一个元素为 0 ,则将其所在行和列的所有元素都设为 0 。请使用原地算法。
示例 1:
输入:matrix = [[1,1,1],[1,0,1],[1,1,1]] 输出:[[1,0,1],[0,0,0],[1,0,1]]
2、初始思路
2.1 思路1
先找出所有0的横纵坐标,然后遍历置零。
class Solution(object):
def setZeroes(self, matrix):
"""
:type matrix: List[List[int]]
:rtype: None Do not return anything, modify matrix in-place instead.
"""
all_i = []
all_j = []
m, n = len(matrix), len(matrix[0])
for i in range(m):
for j in range(n):
if matrix[i][j] == 0:
if i not in all_i:
all_i.append(i)
if j not in all_j:
all_j.append(j)
#print(all_i)
for i in all_i:
for j in range(n):
matrix[i][j] = 0
for j in all_j:
for i in range(m):
matrix[i][j] = 0
return matrix
2.2 思路2
通过设置false来判断0的存在
class Solution(object):
def setZeroes(self, matrix):
"""
:type matrix: List[List[int]]
:rtype: None Do not return anything, modify matrix in-place instead.
"""
m, n = len(matrix), len(matrix[0])
m_0 = m * [False]
n_0 = n * [False]
for i in range(m):
for j in range(n):
if matrix[i][j] == 0:
m_0[i] = True
n_0[j] = True
for i in range(m):
for j in range(n):
if m_0[i] or n_0[j]:
matrix[i][j] = 0
3、总结
1、矩阵的行列计算为
行
m = len(matrix)
列
n = len(matrix[0])
2、python中False和True首字母要大写