leecode_python中档题:73. 矩阵置零

给定一个 m x n 的矩阵,如果一个元素为 0,则将其所在行和列的所有元素都设为 0。请使用原地算法。
要注意第一行和第一列置零的技巧

class Solution(object):
    def setZeroes(self, matrix):
        """
        :type matrix: List[List[int]]
        :rtype: None Do not return anything, modify matrix in-place instead.
        """
        idm, idn = [], []
        m, n = len(matrix), len(matrix[0])
        zero_row, zero_col = False, False
        
        for i in range(m):
            for j in range(n):
                if matrix[i][j] == 0:
                    matrix[i][0] = matrix[0][j] = 0
                    zero_row = True if i == 0 else zero_row
                    zero_col = True if j == 0 else zero_col
        
        for j in range(1,n):
            if matrix[0][j] == 0:
                for i in range(1,m):
                    matrix[i][j] = 0
                    
        for i in range(1,m):
            if matrix[i][0] == 0:
                for j in range(1,n):
                    matrix[i][j] = 0

        if zero_row:
            for j in range(n):
                matrix[0][j] = 0

        if zero_col:
            for i in range(m):
                matrix[i][0] = 0

        return matrix        

你可能感兴趣的:(leecode,算法,python,leetcode,数据结构,线性代数)