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.
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值