File tree Expand file tree Collapse file tree 1 file changed +42
-0
lines changed Expand file tree Collapse file tree 1 file changed +42
-0
lines changed Original file line number Diff line number Diff line change 1+ // Time: O(m * n)
2+ // Space: O(1) + output array
3+ function spiralOrder ( matrix ) {
4+ const result = [ ] ;
5+
6+ let top = 0 ;
7+ let bottom = matrix . length - 1 ;
8+ let left = 0 ;
9+ let right = matrix [ 0 ] . length - 1 ;
10+
11+ while ( top <= bottom && left <= right ) {
12+ // 1. μΌ β μ€
13+ for ( let i = left ; i <= right ; i ++ ) {
14+ result . push ( matrix [ top ] [ i ] ) ;
15+ }
16+ top ++ ;
17+
18+ // 2. μ β μλ
19+ for ( let i = top ; i <= bottom ; i ++ ) {
20+ result . push ( matrix [ i ] [ right ] ) ;
21+ }
22+ right -- ;
23+
24+ // 3. μ€ β μΌ
25+ if ( top <= bottom ) {
26+ for ( let i = right ; i >= left ; i -- ) {
27+ result . push ( matrix [ bottom ] [ i ] ) ;
28+ }
29+ bottom -- ;
30+ }
31+
32+ // 4. μλ β μ
33+ if ( left <= right ) {
34+ for ( let i = bottom ; i >= top ; i -- ) {
35+ result . push ( matrix [ i ] [ left ] ) ;
36+ }
37+ left ++ ;
38+ }
39+ }
40+
41+ return result ;
42+ }
You canβt perform that action at this time.
0 commit comments