[NeetCode 150] Set Zeroes in Matrix

Set Zeroes in Matrix

Given an m x n matrix of integers matrix, if an element is 0, set its entire row and column to 0’s.

You must update the matrix in-place.

Follow up: Could you solve it using O(1) space?

Example 1:

Input: matrix = [
  [0,1],
  [1,1]
]

Output: [
  [0,0],
  [0,1]
]

Example 2:

Input: matrix = [
  [1,2,3],
  [4,0,5],
  [6,7,8]
]

Output: [
  [1,0,3],
  [0,0,0],
  [6,0,8]
]

Constraints:

1 <= matrix.length, matrix[0].length <= 100
-2^31 <= matrix[i][j] <= (2^31) - 1

Solution

To achieve O(1)O(1)O(1) extra space, we have to reuse the space in matrix to mark the columns we need to set to zero. So, we can keep the first row as the mark row. An additional variable is applied to mark whether the first row need to be set to zero. Then, go through other rows, if zero exists, set the corresponding column in the first row to zero, set the whole row to zero afterwards. Finally, set columns to zero according to the mark in first row.

Code

class Solution:
    def setZeroes(self, matrix: List[List[int]]) -> None:
        zero_in_first_row = False
        for i in range(len(matrix[0])):
            if matrix[0][i] == 0:
                zero_in_first_row = True
                break

        for i in range(1, len(matrix)):
            zero = False
            for j in range(len(matrix[0])):
                if matrix[i][j] == 0:
                    zero = True
                    matrix[0][j] = 0
            if zero:
                for j in range(len(matrix[0])):
                    matrix[i][j] = 0
        
        for i in range(len(matrix[0])):
            if matrix[0][i] == 0:
                for j in range(len(matrix)):
                    matrix[j][i] = 0
        
        if zero_in_first_row:
            for i in range(len(matrix[0])):
                matrix[0][i] = 0
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

ShadyPi

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值