[leetcode]Set Matrix Zeroes @ Python


原題地址:https://oj.leetcode.com/problems/set-matrix-zeroes/

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

解題思路:分別記錄兩個向量x, y,保存行和列是否有0,再次遍歷數組時查詢對應的行和列然后修改值。

代碼:

class Solution:
    # @param matrix, a list of lists of integers
    # RETURN NOTHING, MODIFY matrix IN PLACE.
    def setZeroes(self, matrix):
        rownum = len(matrix)
        colnum = len(matrix[0])
        row = [False for i in range(rownum)]
        col = [False for i in range(colnum)]
        for i in range(rownum):
            for j in range(colnum):
                if matrix[i][j] == 0:
                    row[i] = True
                    col[j] = True
        for i in range(rownum):
            for j in range(colnum):
                if row[i] or col[j]:
                    matrix[i][j] = 0
                    

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM