Set Matrix Zeroes

Given an m x n matrix. If an element is 0, set its entire row and column to 0. Do it in-place. Tags: Matrix

Try It!

Discussion

Video

Solution

class Solution:
    def setZeroes(self, matrix: List[List[int]]) -> None:
        """
        Do not return anything, modify matrix in-place instead.
        """
        top_has_zero = False
        for j in range(len(matrix[0])):
            if matrix[0][j] == 0:
                top_has_zero = True
                break
        
        # Create a marker using first row and column
        # 010
        # 110
        # 001
        for i in range(1, len(matrix)):
            for j in range(len(matrix[0])):
                if matrix[i][j] == 0:
                    matrix[i][0] = 0
                    matrix[0][j] = 0
                    
        # Set the zeros, backwards iterating through the row
        for i in range(1, len(matrix)):
            for j in range(len(matrix[0]) - 1, -1, -1):
                if matrix[i][0] == 0 or matrix[0][j] == 0:
                    matrix[i][j] = 0
        
        if top_has_zero:
            for j in range(len(matrix[0])):
                matrix[0][j] = 0