LeetCode解题之Set Matrix Zeroes
原题
假设矩阵中存在0。那么把0所在的行和列都置为0。要求在所给的矩阵上完毕操作。
注意点:
- 最好仅仅申请常量级的额外空间
样例:
输入:
matrix =
[[1, 0, 1, 1],
[1, 1, 0, 1],
[1, 1, 1, 0],
[1, 1, 1, 1]]
输出:
[[0, 0, 0, 0],
[0, 0, 0, 0],
[0, 0, 0, 0],
[1, 0, 0, 0]]
解题思路
一边遍历,一边将对应的行和列置为0是行不通的。会影响后面元素的遍历推断,所以要记录下哪些行和哪些列是要置为0的。为了节约空间,在原矩阵中借两条边,假设该行或者列要置为0,则把左边或者上边的对应位置置为0。假设左边和上边本来就有0,那么须要额外标记一下,最后把左边或者右边也所有置为0.
AC源代码
class Solution(object):
def setZeroes(self, matrix):
"""
:type matrix: List[List[int]]
:rtype: void Do not return anything, modify matrix in-place instead.
"""
first_row = False
first_col = False
m = len(matrix)
n = len(matrix[0])
for i in range(m):
if matrix[i][0] == 0:
first_col = True
for j in range(n):
if matrix[0][j] == 0:
first_row = True
for i in range(1, m):
for j in range(1, n):
if matrix[i][j] == 0:
matrix[i][0] = matrix[0][j] = 0
for i in range(1, m):
for j in range(1, n):
if matrix[0][j] == 0 or matrix[i][0] == 0:
matrix[i][j] = 0
if first_row:
for j in range(n):
matrix[0][j] = 0
if first_col:
for i in range(m):
matrix[i][0] = 0
if __name__ == "__main__":
matrix = [[1, 0, 1, 1],
[1, 1, 0, 1],
[1, 1, 1, 0],
[1, 1, 1, 1]]
Solution().setZeroes(matrix)
assert matrix == [[0, 0, 0, 0],
[0, 0, 0, 0],
[0, 0, 0, 0],
[1, 0, 0, 0]]
欢迎查看我的Github (https://github.com/gavinfish/LeetCode-Python) 来获得相关源代码。