Original link: https://leetcode.com/problems/set-matrix-zeroes/
This question is tricky. The very intuitive thinking is to set 0 in-place, which seems to be very fast and use least space. However, there is one problem, that is, what if there are two (or more) zeros in one line/column? We meet the first 0 and begin to “set 0”. When we meet the second zero, we get into trouble. We cannot use a recursive way to solve it. Consider the following case:
Input =
[[ 0 1 0]
[1 2 1]
[0 1 0]]
We begin with the first 0 and set the first row as all-0s. And we will see the one in [0][2]. We might set the last column as all-0s and meet another 0 in [2][2]. When we go around and begin to set the first column as all-0s, we find the very first 0.
We can add some conditions to aviod getting into a infinite loop like to see if the entire row/column is already all-0s. However, we may have to implement another function and this function requires another input (whether we are cleaning one row or one column). What’s more, this kind of implementation still need to iterate all matrix, which cannot help to accelerate the program.
As discribed above, and also according to the hint, we need to somehow store the information of 0s. We can use a matirx which has a same size as the input. We can also use two vectors (arrays) to store which column/row should be cleaned. I think the optimal way is to use two HashMaps to store the information.
Code:
class Solution(object):
def setZeroes(self, matrix):
"""
:type matrix: List[List[int]]
:rtype: None Do not return anything, modify matrix in-place instead.
"""
row_d = set()
col_d = set()
for r in range(len(matrix)):
for c in range(len(matrix[0])):
if matrix[r][c] == 0:
row_d.add(r)
col_d.add(c)
for r in row_d:
matrix[r] = [0 for i in range(len(matrix[0]))]
for c in col_d:
for r in range(len(matrix)):
matrix[r][c] = 0