Search This Blog

Saturday, January 18, 2014

Write an algorithm such that if an element in an MxN matrix is 0, its entire row and column is set to 0.

#!/usr/bin/python

a=[[1,2,3],[4,5,6],[7,0,0],[10,9,12]]
#a=[[10,7,4,1],[17,0,5,2],[12,9,6,3]]
num_of_rows=len(a)
num_of_col=len(a[0])

#### Using dictionary here but it is a bug because dict replacing the value if same key found :-)
def matrix_wd_zero():
    m_dict={}
    print "Given Matrix : ", a
    for i in range(num_of_rows):
        for j in range(num_of_col):
            m_value=a[i][j]
            if m_value == 0:
                m_dict[i]=j
    for i,j in m_dict.items():
        for k in range(num_of_col):
            a[i][k]=0
        for p in range(num_of_rows):
            a[p][j]=0
    print "Result Matrix : ", a


############ Efficient and correct Function
def matrix_wd_zero2():
    print "Given Matrix : ", a
    for i in range(num_of_rows):
        for j in range(num_of_col):
            if a[i][j]==0:
                for k in range(num_of_col):
                    a[i][k]=100
                for p in range(num_of_rows):
                    a[p][j]=100
    for i in range(num_of_rows):
        for j in range(num_of_col):
            if a[i][j]==100:
                a[i][j]=0
    print "Result Matrix : ", a

if __name__=='__main__':
    #matrix_wd_zero()
    matrix_wd_zero2()

No comments:

My Profile

My photo
can be reached at 09916017317