Leetcode-73. Set Matrix Zeroes

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
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值