Best Solution in Python using O(1) and beating 99.9%


  • 0
    U
    class Solution(object):
        def setZeroes(self, matrix):
            """
            :type matrix: List[List[int]]
            :rtype: void Do not return anything, modify matrix in-place instead.
            """
            row = len(matrix)
            column = len(matrix[0])
            
            first_row = False
            first_column = False
            
            for i in range(row):
                for j in range(column):
                    if matrix[i][j] == 0:
                        if i == 0:
                            first_row = True
                        if j == 0:
                            first_column = True
                        
                        matrix[i][0] = 0
                        matrix[0][j] = 0
            
            for i in range(1, row):
                if matrix[i][0] == 0:
                    for j in range(1, column):
                        matrix[i][j] = 0
                if matrix[0][0] == 0 and first_column:
                    matrix[i][0] = 0
                    
                        
            for j in range(1, column):
                if matrix[0][j] == 0:
                    for i in range(1, row):
                        matrix[i][j] = 0
                if matrix[0][0] == 0 and first_row:
                    matrix[0][j] = 0
                
                
                
            
                    
                        
    

Log in to reply
 

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