|
| 1 | +from itertools import product |
| 2 | + |
| 3 | + |
| 4 | +class Solution: |
| 5 | + def setZeroes(self, matrix: list[list[int]]) -> list[list[int]]: |
| 6 | + rows, cols = len(matrix), len(matrix[0]) |
| 7 | + first_row_zero, first_col_zero = False, False |
| 8 | + |
| 9 | + for row, col in product(range(rows), range(cols)): |
| 10 | + if matrix[row][col] == 0: |
| 11 | + if row == 0: |
| 12 | + first_row_zero = True |
| 13 | + if col == 0: |
| 14 | + first_col_zero = True |
| 15 | + matrix[row][0] = None |
| 16 | + matrix[0][col] = None |
| 17 | + |
| 18 | + for row in range(1, rows): |
| 19 | + if matrix[row][0] is None: |
| 20 | + for col in range(cols): |
| 21 | + matrix[row][col] = 0 |
| 22 | + for col in range(1, cols): |
| 23 | + if matrix[0][col] is None: |
| 24 | + for row in range(rows): |
| 25 | + matrix[row][col] = 0 |
| 26 | + |
| 27 | + if first_col_zero is True: |
| 28 | + for row in range(rows): |
| 29 | + matrix[row][0] = 0 |
| 30 | + if first_row_zero is True: |
| 31 | + for col in range(cols): |
| 32 | + matrix[0][col] = 0 |
| 33 | + |
| 34 | + |
| 35 | +def main(): |
| 36 | + matrix = [[1, 1, 1], [1, 0, 1], [1, 1, 1]] |
| 37 | + Solution().setZeroes(matrix) |
| 38 | + assert matrix == [[1, 0, 1], [0, 0, 0], [1, 0, 1]] |
| 39 | + |
| 40 | + matrix = [[0, 1, 2, 0], |
| 41 | + [3, 4, 5, 2], |
| 42 | + [1, 3, 1, 5]] |
| 43 | + Solution().setZeroes(matrix) |
| 44 | + assert matrix == [[0, 0, 0, 0], |
| 45 | + [0, 4, 5, 0], |
| 46 | + [0, 3, 1, 0]] |
| 47 | + |
| 48 | + matrix = [[1, 2, 3, 4], |
| 49 | + [5, 0, 7, 8], |
| 50 | + [0, 10, 11, 12], |
| 51 | + [13, 14, 15, 0]] |
| 52 | + Solution().setZeroes(matrix) |
| 53 | + assert matrix == [[0, 0, 3, 0], |
| 54 | + [0, 0, 0, 0], |
| 55 | + [0, 0, 0, 0], |
| 56 | + [0, 0, 0, 0]] |
| 57 | + |
| 58 | + |
| 59 | +if __name__ == '__main__': |
| 60 | + main() |
0 commit comments