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+ * https://leetcode.com/problems/spiral-matrix/
3+ * @param {number[][] } matrix
4+ * @return {number[] }
5+ */
6+ var spiralOrder = function ( matrix ) {
7+ const result = [ ] ;
8+ if ( matrix . length === 0 ) return result ;
9+
10+ let top = 0 ;
11+ let bottom = matrix . length - 1 ;
12+ let left = 0 ;
13+ let right = matrix [ 0 ] . length - 1 ;
14+
15+ while ( top <= bottom && left <= right ) {
16+ // 1. ์ข -> ์ฐ
17+ for ( let col = left ; col <= right ; col ++ ) {
18+ result . push ( matrix [ top ] [ col ] ) ;
19+ }
20+ top ++ ; // ์์ชฝ ๊ฒฝ๊ณ ํ ์ค ์๋๋ก ์ด๋
21+
22+ // 2. ์ -> ์๋
23+ for ( let row = top ; row <= bottom ; row ++ ) {
24+ result . push ( matrix [ row ] [ right ] ) ;
25+ }
26+ right -- ; // ์ค๋ฅธ์ชฝ ๊ฒฝ๊ณ ์ผ์ชฝ์ผ๋ก ์ด๋
27+
28+ // 3. ์ฐ -> ์ข
29+ if ( top <= bottom ) {
30+ for ( let col = right ; col >= left ; col -- ) {
31+ result . push ( matrix [ bottom ] [ col ] ) ;
32+ }
33+ bottom -- ; // ์๋์ชฝ ๊ฒฝ๊ณ ์๋ก ์ด๋
34+ }
35+
36+ // 4. ์๋ -> ์
37+ if ( left <= right ) {
38+ for ( let row = bottom ; row >= top ; row -- ) {
39+ result . push ( matrix [ row ] [ left ] ) ;
40+ }
41+ left ++ ; // ์ผ์ชฝ ๊ฒฝ๊ณ ์ค๋ฅธ์ชฝ์ผ๋ก ์ด๋
42+ }
43+ }
44+
45+ return result ;
46+ } ;
You canโt perform that action at this time.
0 commit comments