6/02/2020

[LeetCode] 73. Set Matrix Zeroes

Problem : https://leetcode.com/problems/set-matrix-zeroes/

Allocate extra space to record columns or rows have 0.
Space complexity O ( ROW + COLUMN ) solution. 

class Solution:
    def setZeroes(self, matrix: List[List[int]]) -> None:
        """
        Do not return anything, modify matrix in-place instead.
        """
        
        ROW = len(matrix)
        COLUMN = len(matrix[0])
        
        mark = [False] * (ROW + COLUMN)
        
        for y in range(ROW):
            for x in range(COLUMN):
                if matrix[y][x] == 0:
                    mark[y] = True
                    mark[ROW + x] = True
        
        # set zeros 
        for y in range(ROW):
            for x in range(COLUMN):
                if mark[y] or mark[ROW + x]:
                    matrix[y][x] = 0

Edited on 08/13/2021. Simplify the O(ROW + COLUMN) solution.

No comments:

Post a Comment