File tree Expand file tree Collapse file tree 1 file changed +48
-0
lines changed Expand file tree Collapse file tree 1 file changed +48
-0
lines changed Original file line number Diff line number Diff line change
1
+ /**
2
+ * @param {number[][] } matrix
3
+ * @return {number[] }
4
+ */
5
+ var spiralOrder = function ( matrix ) {
6
+ let top = 0 ; // 상단 행 인덱스
7
+ let bottom = matrix . length - 1 ; // 하단 행 인덱스
8
+ let left = 0 ; // 좌측 열 인덱스
9
+ let right = matrix [ 0 ] . length - 1 ; // 우측 열 인덱스
10
+
11
+ const answer = [ ] ;
12
+
13
+ // 상단, 우측, 하단, 좌측 경계를 차례로 순회하며 값을 수집
14
+ // 각 반복마다 경계가 안쪽으로 줄어듦
15
+ while ( top <= bottom && left <= right ) {
16
+ // 1. 상단 행 순회
17
+ for ( let col = left ; col <= right ; col ++ ) {
18
+ answer . push ( matrix [ top ] [ col ] ) ;
19
+ }
20
+ top ++ ; // 상단 경계를 아래로 한칸 이동
21
+ // 상단 경계가 하단 경계를 넘어가면 중단
22
+ if ( top > bottom ) {
23
+ break ;
24
+ }
25
+ // 2. 우측 열 순회
26
+ for ( let row = top ; row <= bottom ; row ++ ) {
27
+ answer . push ( matrix [ row ] [ right ] ) ;
28
+ }
29
+ right -- ; // 우측 경계를 왼쪽으로 한칸 이동
30
+ // 우측 경계가 좌측 경계를 넘어가면 중단
31
+ if ( left > right ) {
32
+ break ;
33
+ }
34
+ // 3. 하단 행 순회
35
+ for ( let col = right ; col >= left ; col -- ) {
36
+ answer . push ( matrix [ bottom ] [ col ] ) ;
37
+ }
38
+ bottom -- ; // 하단 경계를 위쪽으로 한칸 이동
39
+
40
+ // 4. 좌측 열 순회
41
+ for ( let row = bottom ; row >= top ; row -- ) {
42
+ answer . push ( matrix [ row ] [ left ] ) ;
43
+ }
44
+ left ++ ; // 좌측 경계를 우측으로 한칸 이동
45
+ }
46
+
47
+ return answer ;
48
+ } ;
You can’t perform that action at this time.
0 commit comments