Saturday, May 17, 2014

Leetcode (Python): Set Matrix Zeroes

Given a m x n matrix, if an element is 0, set its entire row and column to 0. Do it in place.

Solution:

We could use two arrays to mark the rows and cols that have a zero in it, but to use constant space we can use the first row and column (or any other). As afterwards we do not know if this row and col had at the beginning a zero or not, we save this information before modifying them.

class Solution:
    # @param matrix, a list of lists of integers
    # RETURN NOTHING, MODIFY matrix IN PLACE.
    def setZeroes(self, matrix):
        firstRowHasZero = False
        firstColHasZero = False
        if len(matrix)==0 or len(matrix[0]) == 0:
            return
        for col in range(0,len(matrix[0])):
            if matrix[0][col]==0:
                firstRowHasZero = True
                break
        for row in range(0, len(matrix)):
            if matrix[row][0]==0:
                firstColHasZero = True
                break
            
        for row in range(1, len(matrix)):
            for col in range(1,len(matrix[0])):
                if matrix[row][col] == 0:
                    matrix[0][col] = 0
                    matrix[row][0] = 0
        
        for row in range(1, len(matrix)):
            for col in range(1,len(matrix[0])):
                if matrix[row][0] == 0 or matrix[0][col] == 0:
                    matrix[row][col] = 0
        
        if firstRowHasZero:
            for col in range(0,len(matrix[0])):
                matrix[0][col] = 0
        
        if firstColHasZero:
            for row in range(0, len(matrix)):
                matrix[row][0] = 0

No comments :

Post a Comment