# @lc code=start classSolution: defsetZeroes(self, matrix: List[List[int]]) -> None: """ Do not return anything, modify matrix in-place instead. """ ifnot matrix: return [] row_zero = set() col_zero = set() for i inrange(len(matrix)): for j inrange(len(matrix[0])): if matrix[i][j] == 0: row_zero.add(i) col_zero.add(j) for i inrange(len(matrix)): for j inrange(len(matrix[0])): if i in row_zero or j in col_zero: matrix[i][j] = 0 # @lc code=end
classSolution(object): defsetZeroes(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]) for i inrange(R): # Since first cell for both first row and first column is the same i.e. matrix[0][0] # We can use an additional variable for either the first row/column. # For this solution we are using an additional variable for the first column # and using matrix[0][0] for the first row. if matrix[i][0] == 0: is_col = True for j inrange(1, C): # If an element is zero, we set the first element of the corresponding row and column to 0 if matrix[i][j] == 0: matrix[0][j] = 0 matrix[i][0] = 0
# Iterate over the array once again and using the first row and first column, update the elements. for i inrange(1, R): for j inrange(1, C): ifnot matrix[i][0] ornot matrix[0][j]: matrix[i][j] = 0
# See if the first row needs to be set to zero as well if matrix[0][0] == 0: for j inrange(C): matrix[0][j] = 0