目前能想到的方法是首先创建一个列表,长度为矩阵行数,初始化为全0,创建一个列表,长度为矩阵列数目,初始化为全0,然后扫描整个矩阵,扫描到0时相应的行和列标记为1,再扫描行和列列表,修改矩阵,代码如下:
class Solution(object):
def setZeroes(self, matrix):
"""
:type matrix: List[List[int]]
:rtype: void Do not return anything, modify matrix in-place instead.
"""
m = len(matrix)
n = len(matrix[0])
row = [0 for i in range(m)]
colum = [0 for j in range(n)]
for i in range(m):
for j in range(n):
if matrix[i][j] == 0:
row[i] = 1
colum[j] = 1
for i in range(m):
if row[i] == 1:
for j in range(n):
matrix[i][j] = 0
for i in range(n):
if colum[i] == 1:
for j in range(m):
matrix[j][i] = 0
第二种是经过看了网上的想法写的一个代码,用第一行和第一列来记录,不开辟额外空间,但是事先需要扫面第一行第一列中是否有0值,用两个变量记录。中间还有一些顺序的调节,总之bug没完,我决定把代码贴上来以后看看别人的思考过程是不是有我写的这么复杂。
class Solution(object):
def setZeroes(self, matrix):
"""
:type matrix: List[List[int]]
:rtype: void Do not return anything, modify matrix in-place instead.
"""
#不使用额外空间
m = len(matrix)
n = len(matrix[0])
r = 1
c = 1
for i in range(m):
if matrix[i][0] == 0:
r = 0
for j in range(n):
if matrix[0][j] == 0:
c = 0
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
for i in range(1,m-1):
if matrix[i][0] == 0:
for j in range(1,n):
matrix[i][j] = 0
for j in range(1,n-1):
if matrix[0][j] == 0:
for i in range(1,m):
matrix[i][j] = 0
if matrix[0][n-1] == 0:
for i in range(m):
matrix[i][n-1] = 0
if matrix[m-1][0] == 0:
for j in range(n):
matrix[m-1][j] = 0
if r == 0:
for i in range(m):
matrix[i][0] = 0
if c == 0:
for j in range(n):
matrix[0][j] = 0
模仿别人来的一种方法,但是没我的繁琐行快哈哈哈哈哈哈,代码如下:
class Solution(object):
def setZeroes(self, matrix):
"""
:type matrix: List[List[int]]
:rtype: void Do not return anything, modify matrix in-place instead.
"""
#不使用额外空间
m = len(matrix)
n = len(matrix[0])
r = 1
c = 1
for i in range(m):
if matrix[i][0] == 0:
r = 0
break
for j in range(n):
if matrix[0][j] == 0:
c = 0
break
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
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 r == 0:
for i in range(m):
matrix[i][0] = 0
if c == 0:
for j in range(n):
matrix[0][j] = 0