# time O(N+M) space O(MN)
class Solution:
    def setZeroes(self, matrix: List[List[int]]) -> None:
        """
        Do not return anything, modify matrix in-place instead.
        """
        seen = set()
        q = []
        row = len(matrix)
        col = len(matrix[0])
        for i in range(row):
            for j in range(col):
                if matrix[i][j] == 0:
                    q.append((i,j))
                    seen.add((i,j))
        
        for each in q:
            x = each[0]
            y = each[1]
            # row set to  0 
            for i in range(row):
                if (i,y) not in seen:
                    seen.add((i,y))
                    matrix[i][y] = 0
            for j in range(col):
                if (x,j) not in seen:
                    seen.add((x,j))
                    matrix[x][j] = 0

optimal solution

# time O(MN)  space O(M+N)
class Solution(object):
    def setZeroes(self, matrix):
        """
        :type matrix: List[List[int]]
        :rtype: void Do not return anything, modify matrix in-place instead.
        """
        R = len(matrix)
        C = len(matrix[0])
        rows, cols = set(), set()

        # Essentially, we mark the rows and columns that are to be made zero
        for i in range(R):
            for j in range(C):
                if matrix[i][j] == 0:
                    rows.add(i)
                    cols.add(j)

        # Iterate over the array once again and using the rows and cols sets, update the elements
        for i in range(R):
            for j in range(C):
                if i in rows or j in cols:
                    matrix[i][j] = 0

optimization: Space O(1) time O(R*C)

class Solution(object):
    def setZeroes(self, matrix):
        """
        :type matrix: List[List[int]]
        :rtype: void Do not return anything, modify matrix in-place instead.
        """
        is_col = False
        R = len(matrix)
        C = len(matrix[0])
        

        # Essentially, we mark the rows and columns that are to be made zero
        for i in range(R):
            if matrix[i][0]==0:
                is_col = True
            for j in range(1,C):
                if matrix[i][j] == 0:
                    matrix[i][0] = 0
                    matrix[0][j] = 0
                # Iterate over the array once again and using the rows and cols sets, update the elements
        for i in range(1,R):
            for j in range(1,C):
                if matrix[i][0] == 0 or matrix[0][j] == 0:
                    matrix[i][j] = 0
        
        
        if matrix[0][0] == 0:
            for j in range(C):
                matrix[0][j] = 0
        
        
        if is_col:
            for i in range(R):
                matrix[i][0] = 0