Idea is as follow:
Its only necessary to find out which row and column contains 0. After this step, change all elements in certain row and column to 0. If no 0 exists, do nothing.
# Two sets that record which row and column has 0 rowSet = set() colSet = set() # Iterate each element. # If it is 0, record row and column number for r in range(len(matrix)): for c in range(len(matrix)): if matrix[r][c] == 0: rowSet.add(r) colSet.add(c) # Change all rows containing 0 to 0 for r in rowSet: for c in range(len(matrix)): matrix[r][c] = 0 # Change all columns containing 0 to 0 for c in colSet: for r in range(len(matrix)): matrix[r][c] = 0