|
3 | 3 |
|
4 | 4 | class Solution: |
5 | 5 | def setZeroes(self, matrix: List[List[int]]) -> None: |
6 | | - """ |
7 | | - Do not return anything, modify matrix in-place instead. |
8 | | - """ |
9 | | - if not matrix or not matrix[0]: |
10 | | - return |
11 | | - |
12 | 6 | rows, cols = len(matrix), len(matrix[0]) |
13 | | - first_row_has_zero = any(matrix[0][j] == 0 for j in range(cols)) |
14 | | - first_col_has_zero = any(matrix[i][0] == 0 for i in range(rows)) |
15 | | - |
16 | | - # Use the first row and first column to mark zeros |
17 | | - for i in range(1, rows): |
18 | | - for j in range(1, cols): |
19 | | - if matrix[i][j] == 0: |
20 | | - matrix[0][j] = 0 |
21 | | - matrix[i][0] = 0 |
22 | | - |
23 | | - # Set matrix elements to zero based on marks |
24 | | - for i in range(1, rows): |
25 | | - for j in range(1, cols): |
26 | | - if matrix[0][j] == 0 or matrix[i][0] == 0: |
27 | | - matrix[i][j] = 0 |
28 | | - |
29 | | - # Set the first row to zero if needed |
30 | | - if first_row_has_zero: |
31 | | - for j in range(cols): |
32 | | - matrix[0][j] = 0 |
33 | | - |
34 | | - # Set the first column to zero if needed |
35 | | - if first_col_has_zero: |
36 | | - for i in range(rows): |
37 | | - matrix[i][0] = 0 |
| 7 | + first_row_zero = False |
| 8 | + first_col_zero = False |
| 9 | + |
| 10 | + # 첫 행에 0이 있는지 확인 |
| 11 | + for col in range(cols): |
| 12 | + if matrix[0][col] == 0: |
| 13 | + first_row_zero = True |
| 14 | + break |
| 15 | + |
| 16 | + # 첫 열에 0이 있는지 확인 |
| 17 | + for row in range(rows): |
| 18 | + if matrix[row][0] == 0: |
| 19 | + first_col_zero = True |
| 20 | + break |
| 21 | + |
| 22 | + # 마커 설정 (첫 행과 첫 열을 이용) |
| 23 | + for row in range(1, rows): |
| 24 | + for col in range(1, cols): |
| 25 | + if matrix[row][col] == 0: |
| 26 | + matrix[row][0] = 0 |
| 27 | + matrix[0][col] = 0 |
| 28 | + |
| 29 | + # 마커에 따라 0으로 설정 |
| 30 | + for row in range(1, rows): |
| 31 | + for col in range(1, cols): |
| 32 | + if matrix[row][0] == 0 or matrix[0][col] == 0: |
| 33 | + matrix[row][col] = 0 |
| 34 | + |
| 35 | + # 첫 행 처리 |
| 36 | + if first_row_zero: |
| 37 | + for col in range(cols): |
| 38 | + matrix[0][col] = 0 |
| 39 | + |
| 40 | + # 첫 열 처리 |
| 41 | + if first_col_zero: |
| 42 | + for row in range(rows): |
| 43 | + matrix[row][0] = 0 |
0 commit comments