leetcode Set Matrix Zeroes

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

你可能感兴趣的:(LeetCode,Matrix,73)