|
| 1 | +from typing import List |
| 2 | + |
| 3 | + |
| 4 | +class Solution: |
| 5 | + def spiralOrder(self, matrix: List[List[int]]) -> List[int]: |
| 6 | + """ |
| 7 | + - Idea: ๋ค ๊ฐ์ ํฌ์ธํฐ(left, right, top, bottom)๋ฅผ ํ์ฉํ์ฌ ํ๋ ฌ์ ๋ฐ๊นฅ์ชฝ๋ถํฐ ์์ชฝ์ผ๋ก ์ํํ๋ค. |
| 8 | + - left, right: ํ๋ ฌ์ ์ผ์ชฝ๊ณผ ์ค๋ฅธ์ชฝ ๋. ์ํํ๋ฉด์ ์ ์ ์ขํ์ง๋ค. |
| 9 | + - top, bottom: ํ๋ ฌ์ ์์ชฝ๊ณผ ์๋์ชฝ. ์ํํ๋ฉด์ ์ ์ ์ขํ์ง๋ค. |
| 10 | + - Time Complexity: O(m*n), m, n์ ๊ฐ๊ฐ ์ฃผ์ด์ง ํ๋ ฌ(matrix)์ ํ๊ณผ ์ด์ ๊ฐ์. ํ๋ ฌ์ ๋ชจ๋ ์์๋ฅผ ํ๋ฒ์ฉ ์ ๊ทผํ๋ค. |
| 11 | + - Space Complexity: O(1), ๊ฒฐ๊ณผ ๋ฆฌ์คํธ(result)๋ฅผ ์ ์ธํ๊ณ ํฌ์ธํฐ๋ฅผ ์ํ ์์ ํฌ๊ธฐ์ ๋ณ์ ์ด์ธ์ ์ถ๊ฐ ๊ณต๊ฐ์ ์ฌ์ฉํ์ง ์๋๋ค. |
| 12 | + """ |
| 13 | + result = [] |
| 14 | + left, right = 0, len(matrix[0]) |
| 15 | + top, bottom = 0, len(matrix) |
| 16 | + |
| 17 | + while left < right and top < bottom: |
| 18 | + for i in range(left, right): |
| 19 | + result.append(matrix[top][i]) |
| 20 | + top += 1 |
| 21 | + |
| 22 | + for i in range(top, bottom): |
| 23 | + result.append(matrix[i][right - 1]) |
| 24 | + right -= 1 |
| 25 | + |
| 26 | + if not (left < right and top < bottom): |
| 27 | + break |
| 28 | + |
| 29 | + for i in range(right - 1, left - 1, -1): |
| 30 | + result.append(matrix[bottom - 1][i]) |
| 31 | + bottom -= 1 |
| 32 | + |
| 33 | + for i in range(bottom - 1, top - 1, -1): |
| 34 | + result.append(matrix[i][left]) |
| 35 | + left += 1 |
| 36 | + |
| 37 | + return result |
0 commit comments