File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change 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
You can’t perform that action at this time.
0 commit comments