Skip to content

Latest commit

 

History

History
38 lines (30 loc) · 1.33 KB

73.-set-matrix-zeroes.md

File metadata and controls

38 lines (30 loc) · 1.33 KB

73. Set Matrix Zeroes

  • Medium

  • Given an m x n integer matrix matrix, if an element is 0, set its entire row and column to 0's, and return the matrix.

    You must do it in place.

Analysis

The most simple and naive idea is to go through the matrix searching for 0. When we find one, we change the numbers in that row and column to be "a"(so that it would not be confused with other 0s). Eventually we come back and change all the "a"s back into zero.

This method actually works out pretty well.

class Solution:
    def setZeroes(self, matrix: List[List[int]]) -> None:
        """
        Do not return anything, modify matrix in-place instead.
        """
        m=len(matrix)
        n=len(matrix[0])
        for i in range(m):
            for j in range(n):
                if matrix[i][j]==0:
                    for k in range(m):
                        if matrix[k][j]!=0:
                            matrix[k][j]="a"
                    for l in range(n):
                        if matrix[i][l]!=0:
                            matrix[i][l]="a"
        
        for i in range(m):
            for j in range(n):
                if matrix[i][j]=="a":
                    matrix[i][j]=0