Set Matrix Zeroes in Python

class Solution:
    def setZeroes(self, matrix: List[List[int]]) -> None:
        """
        Do not return anything, modify matrix in-place instead.
        """
        m = len(matrix)  # Number of rows
        n = len(matrix[0])  # Number of columns
        firstRow = False  # Flag to indicate if the first row needs to be set to 0
        firstCol = False  # Flag to indicate if the first column needs to be set to 0

        # Check if the first row contains any zeros
        for j in range(n):
            if matrix[0][j] == 0:
                firstRow = True
                break

        # Check if the first column contains any zeros
        for i in range(m):
            if matrix[i][0] == 0:
                firstCol = True
                break

        # Use the first row and first column to mark the rows and columns to be set to zero
        for i in range(1, m):
            for j in range(1, n):
                if matrix[i][j] == 0:
                    matrix[i][
                        0
                    ] = 0  # Mark the corresponding element in the first column
                    matrix[0][j] = 0  # Mark the corresponding element in the first row

        # Set the marked rows and columns to zero (excluding the first row and first column)
        for i in range(1, m):
            for j in range(1, n):
                if matrix[i][0] == 0 or matrix[0][j] == 0:
                    matrix[i][j] = 0

        # Set the first row to zero if necessary
        if firstRow:
            for j in range(n):
                matrix[0][j] = 0

        # Set the first column to zero if necessary
        if firstCol:
            for i in range(m):
                matrix[i][0] = 0

PrevNext