Setting columns and rows in MxN matrix to 0

Q. Write an algorithm such that if an element in an MxN matrix is 0, its entire rows and columns are set to 0.

def set_zeros(matrix):
    
    zero_rows = [False]*len(matrix)
    zero_columns = [False]*len(matrix[0])
    
    for i in range(len(matrix)):
        for j in range(len(matrix[0])):
            if matrix[i][j] == 0:
                zero_rows[i] = True
                zero_columns[j] = True
                
    for i in range(len(matrix)):
        for j in range(len(matrix[0])):
            if zero_rows[i] or zero_columns[j]:
                matrix[i][j] = 0
                
                
if __name__ == "__main__":
    
    matrix = [[1,0,3,2,4],[0,23,12,3,9],[0,0,0,34,21],[1,2,3,4,5]]
    
    for i in range(len(matrix)):
        print matrix[i]
            

    set_zeros(matrix)
    
    print "\n"
    for i in range(len(matrix)):
        print matrix[i]

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s