O(1) python AC solution


  • 0
    Y
    class Solution:
        # @param {integer[][]} matrix
        # @return {void} Do not return anything, modify matrix in-place instead.
        def setZeroes(self, mtx):
            if not mtx or not mtx[0]:
                return
    
            m, n = len(mtx), len(mtx[0])
    
            is_first_row_zero = is_first_col_zero = False
            for i in range(m):
                if mtx[i][0] == 0:
                    is_first_row_zero = True
            for i in range(n):
                if mtx[0][i] == 0:
                    is_first_col_zero = True
    
            for i in range(1, m):
                for j in range(1, n):
                    if mtx[i][j] == 0:
                        mtx[i][0] = 0
                        mtx[0][j] = 0
    
            for i in range(1, m):
                if mtx[i][0] == 0:
                    for j in range(1, n):
                        mtx[i][j] = 0
    
            for i in range(1, n):
                if mtx[0][i] == 0:
                    for j in range(1, m):
                        mtx[j][i] = 0
    
    
            if is_first_row_zero:
                for i in range(m):
                    mtx[i][0] = 0
    
            if is_first_col_zero:
                for i in range(n):
                    mtx[0][i] = 0

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.