073 Set Matrix Zeroes

073 Set Matrix Zeroes 

这道题唯一有点tricky的地方就是 需要O(1) 的space, 这样就利用第一个行 和第一列作为整个matrix的标记位,再用 row 和 col两个作为第一列和第一个行的标志位

class Solution:
    # @param {integer[][]} matrix
    # @return {void} Do not return anything, modify matrix in-place instead.
    def setZeroes(self, matrix):
        m = len(matrix)
        if m == 0:
            return matrix
        n = len(matrix[0])
        row, col = False, False
        for j in range(0 ,n):
            if matrix[0][j] == 0:
                row = True
                break
        for i in range(0,m):
            if matrix[i][0] == 0:
                col = True
                break
        for i in range(0, m):
            for j in range(0,n):
                if matrix[i][j] == 0:
                    matrix[i][0] = 0
                    matrix[0][j] = 0
        for i in range(1, m):
            for j in range(1,n):
                if matrix[i][0] == 0 or matrix[0][j] == 0:
                    matrix[i][j] = 0
        if row:
            for j in range(0 ,n):
                matrix[0][j] = 0
        if col:
            for i in range(0,m):
                matrix[i][0] = 0

 

posted @ 2015-07-18 02:57  dapanshe  阅读(112)  评论(0编辑  收藏  举报