File tree Expand file tree Collapse file tree 1 file changed +46
-0
lines changed
Expand file tree Collapse file tree 1 file changed +46
-0
lines changed Original file line number Diff line number Diff line change 1+ """
2+ Solution:
3+ 1) 좌우 상하의 경계를 좁혀가며 순회한다.
4+ 2) 탈출 조건으로 result 의 사이즈가 matrix 의 원소 갯수가 같아지는지 확인한다.
5+ (탈출 조건을 좌우 상하 경계가 넘어가는 시험을 기준으로 삼은 솔루션을 봤지만, 정확히 이해는 되지 않아 사이즈 비교로 진행했습니다.)
6+ Time: O(m * n)
7+ Space: O(1)
8+ """
9+
10+
11+ class Solution :
12+ def spiralOrder (self , matrix : List [List [int ]]) -> List [int ]:
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+ if len (result ) == len (matrix [0 ]) * len (matrix ):
23+ break
24+
25+ for i in range (top , bottom ):
26+ result .append (matrix [i ][right - 1 ])
27+ right -= 1
28+
29+ if len (result ) == len (matrix [0 ]) * len (matrix ):
30+ break
31+
32+ for i in range (right - 1 , left - 1 , - 1 ):
33+ result .append (matrix [bottom - 1 ][i ])
34+ bottom -= 1
35+
36+ if len (result ) == len (matrix [0 ]) * len (matrix ):
37+ break
38+
39+ for i in range (bottom - 1 , top - 1 , - 1 ):
40+ result .append (matrix [i ][left ])
41+ left += 1
42+
43+ if len (result ) == len (matrix [0 ]) * len (matrix ):
44+ break
45+
46+ return result
You can’t perform that action at this time.
0 commit comments