且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

leetcode Set Matrix Zeroes

更新时间:2021-12-15 15:26:48

Question

Given a m x n matrix, if an element is 0, set its entire row and column to 0. Do it in place.

Solution

If you have to store some thing, but the problem requires in place solution, you may consider storing it in the array given.

class Solution(object):
    def setZeroes(self, matrix):
        """
        :type matrix: List[List[int]]
        :rtype: void Do not return anything, modify matrix in-place instead.
        """
        if matrix == None or len(matrix) == 0:
            return
        first_col = False
        first_row = False
        for i in xrange(len(matrix[0])):
            if matrix[0][i] == 0:
                first_row = True
                break;
        for i in xrange(len(matrix)):
            if matrix[i][0] == 0:
                first_col = True
                break;
        for i in xrange(1,len(matrix)):
            for j in xrange(1,len(matrix[0])):
                if matrix[i][j] == 0:
                    matrix[i][0] = 0
                    matrix[0][j] = 0
        for i in xrange(1,len(matrix)):
            for j in xrange(1,len(matrix[0])):
                if matrix[i][0] == 0 or matrix[0][j] == 0:
                    matrix[i][j] = 0
        if first_row:
            for i in xrange(len(matrix[0])):
                matrix[0][i] = 0
        if first_col:
            for i in xrange(len(matrix)):
                matrix[i][0] = 0