|
| 1 | +class Solution: |
| 2 | + def spiralOrder(self, matrix: list[list[int]]) -> list[int]: |
| 3 | + """ |
| 4 | + ์ฃผ์ด์ง 2D ํ๋ ฌ์ ๋์ ํ์ผ๋ก ์ํํ์ฌ ์์๋ค์ ๋ฐํํ๋ ํจ์ |
| 5 | +
|
| 6 | + ๋ฐฉ๋ฒ: |
| 7 | + 1. transpose ํ๋ ฌ์ ๋ง๋ค์ด ์ด์ ์ฝ๊ฒ ์ ๊ทผํ ์ ์๋๋ก ํจ |
| 8 | + 2. while ๋ฃจํ๋ฅผ ์ฌ์ฉํ์ฌ ๋์ ํ์ผ๋ก ์ํ |
| 9 | + 3. ๊ฐ ๋จ๊ณ์์ top row, right column, bottom row, left column์ ์์๋๋ก ์ถ๊ฐ |
| 10 | + 4. ๊ฐ ๋จ๊ณ๊ฐ ๋๋ ๋๋ง๋ค row์ col์ ์ฆ๊ฐ์์ผ ๋ค์ ๋ ์ด์ด๋ก ์ด๋ |
| 11 | +
|
| 12 | + ์๊ฐ๋ณต์ก๋ O(m*n), ๊ณต๊ฐ๋ณต์ก๋ O(m*n) |
| 13 | +
|
| 14 | + Args: |
| 15 | + matrix (list[list[int]]): 2D ํ๋ ฌ |
| 16 | +
|
| 17 | + Returns: |
| 18 | + list[int]: ๋์ ํ์ผ๋ก ์ํํ ์์๋ค์ ๋ฆฌ์คํธ |
| 19 | + """ |
| 20 | + row, col = 0, 0 |
| 21 | + m, n = len(matrix), len(matrix[0]) |
| 22 | + t_matrix = list(zip(*matrix)) |
| 23 | + spiral = [] |
| 24 | + while row < m and col < n: |
| 25 | + top, left = row, col |
| 26 | + bottom, right = m - row - 1, n - col - 1 |
| 27 | + if top > bottom or left > right: |
| 28 | + break |
| 29 | + # first row: left -> right |
| 30 | + first_row = matrix[top][left : right + 1] |
| 31 | + spiral += first_row |
| 32 | + # last col: top+1 -> bottom |
| 33 | + last_col = list(t_matrix[right][top + 1 : bottom + 1]) |
| 34 | + spiral += last_col |
| 35 | + # last row: right-1 -> left (์ญ์) |
| 36 | + if top < bottom: |
| 37 | + last_row = matrix[bottom][left:right][::-1] |
| 38 | + spiral += last_row |
| 39 | + # first col: bottom-1 -> top+1 (์ญ์) |
| 40 | + if left < right: |
| 41 | + first_col = list(t_matrix[left][top + 1 : bottom][::-1]) |
| 42 | + spiral += first_col |
| 43 | + # add |
| 44 | + row += 1 |
| 45 | + col += 1 |
| 46 | + return spiral |
0 commit comments