Chapter 1 Arrays and Strings - 1.7

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

At the first glance, we can just iterate the matrix and when we find a zero, we set the whole row and column to be zero. However, if we write down a simple instance to verify the solution, we can find it's totally wrong. Changing the matrix is not reasonable because we need to differentiate zeros in original matrix from zeros we set.

The second idea is having MXN flags and mark the positions that should be set to zeros. This one is desirable, but not the best one, because it takes O(MXN) space, which can be reduced.

A better solution is given below:
def set_zeros(Mat, M, N):
    row_flags = [False for i in range(0, M)]
    col_flags = [False for i in range(0, N)]
    
    # Mark each row and column that has zero
    for i in range(0, M):
        for j in range(0, N):
            if Mat[i][j] == 0:
                row_flags[i] = True
                col_flags[j] = True

    # Set zeros of each marked row
    for i in range(0, M):
        if row_flags[i] == True:
            for j in range(0, N):
                Mat[i][j] = 0

    # Set zeros of each marked column
    for j in range(0, N):
        if col_flags[j] == True:
            for i in range(0, M):
                Mat[i][j] = 0

# Test case
if __name__ == "__main__":
    Mat = [[0, 0, 2, 3, 4], [4, 5, 6, 7, 8], [9, 1, 1, 2, 0]]
    set_zeros(Mat, 3, 5)
    for i in range(0, len(Mat)):
        for j in range(0, len(Mat[i])):
            print Mat[i][j], " ",
        print "\n"

Lesson: write down simple instance to verify the solution and it will prevent naive mistakes.
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章