Set Matrix Zeroes

Problem Id: 73 Difficulty: Medium Tag: Array


Intuition

One tricky thing in this problem is that, if a 0 is a generated one, not an original one, we should not set it's column and row to 0.

So we need to first set all the values to some unique value. Then, we set these unique values to 0.

Solution


class Solution:
    def setZeroes(self, matrix: List[List[int]]) -> None:
        """
        Do not return anything, modify matrix in-place instead.
        """
        if not matrix:
            return

        m, n = len(matrix), len(matrix[0])
        for i in range(m):
            for j in range(n):
                if matrix[i][j] == 0:
                    for x in range(m):
                        if matrix[x][j] != 0:
                            matrix[x][j] = None
                    for y in range(n):
                        if matrix[i][y] != 0:
                            matrix[i][y] = None

        for i in range(m):
            for j in range(n):
                if matrix[i][j] is None:
                    matrix[i][j] = 0