73. Set Matrix Zeroes

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

def setZeroes(matrix):        
    R, C = len(matrix), len(matrix[0])        
    zero_first_row = False
    zero_first_col = False
   
    for c in range(C):
        if not matrix[0][c]:
            zero_first_row = True
           
    for r in range(R):
        if not matrix[r][0]:
            zero_first_col = True
   
    for r in range(1,R):
        for c in range(1,C):                
            if not matrix[r][c]:                
                matrix[0][c] = 0
                matrix[r][0] = 0
                               
    for r in range(1,R):
        for c in range(1, C):
            if not matrix[0][c] or not matrix[r][0]:
                matrix[r][c] = 0
               
    if zero_first_row:
        for c in range(C):
            matrix[0][c] = 0
           
    if zero_first_col:
        for r in range(R):
            matrix[r][0] = 0


Comments

Popular posts from this blog

849. Maximize Distance to Closest Person

347. Top K Frequent Elements

139. Word Break