如果矩陣中存在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.
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]]