File tree Expand file tree Collapse file tree 1 file changed +32
-0
lines changed
Expand file tree Collapse file tree 1 file changed +32
-0
lines changed Original file line number Diff line number Diff line change 1+ /**
2+ * https://leetcode.com/problems/spiral-matrix/
3+ * time complexity : O(m * n)
4+ * space complexity : O(m * n)
5+ */
6+
7+ function spiralOrder ( matrix : number [ ] [ ] ) : number [ ] {
8+ let [ left , right ] = [ 0 , matrix [ 0 ] . length - 1 ] ;
9+ let [ top , bottom ] = [ 0 , matrix . length - 1 ] ;
10+
11+ const output = [ ] as number [ ] ;
12+
13+ while ( top <= bottom && left <= right ) {
14+ for ( let i = left ; i <= right ; i ++ ) output . push ( matrix [ top ] [ i ] ) ;
15+ top ++ ;
16+
17+ for ( let i = top ; i <= bottom ; i ++ ) output . push ( matrix [ i ] [ right ] ) ;
18+ right -- ;
19+
20+ if ( top <= bottom ) {
21+ for ( let i = right ; i >= left ; i -- ) output . push ( matrix [ bottom ] [ i ] ) ;
22+ bottom -- ;
23+ }
24+
25+ if ( left <= right ) {
26+ for ( let i = bottom ; i >= top ; i -- ) output . push ( matrix [ i ] [ left ] ) ;
27+ left ++ ;
28+ }
29+ }
30+
31+ return output ;
32+ } ;
You can’t perform that action at this time.
0 commit comments