File tree Expand file tree Collapse file tree 1 file changed +41
-0
lines changed Expand file tree Collapse file tree 1 file changed +41
-0
lines changed Original file line number Diff line number Diff line change
1
+ /**
2
+ * @param {number[][] } matrix
3
+ * @return {number[] }
4
+ */
5
+ const spiralOrder = function ( matrix ) {
6
+ const res = [ ]
7
+ let dir = 'top'
8
+ while ( matrix . length ) {
9
+ switch ( dir ) {
10
+ case 'top' :
11
+ res . push ( ...matrix . shift ( ) )
12
+ dir = 'right'
13
+ break ;
14
+ case 'right' :
15
+ for ( let i = 0 ; i < matrix . length - 1 ; ) {
16
+ res . push ( matrix [ i ] . pop ( ) )
17
+ if ( matrix [ i ] . length === 0 ) {
18
+ matrix . splice ( i , 1 )
19
+ } else {
20
+ i ++
21
+ }
22
+ }
23
+ dir = 'bottom'
24
+ break ;
25
+ case 'bottom' :
26
+ res . push ( ...matrix . pop ( ) . reverse ( ) )
27
+ dir = 'left'
28
+ break ;
29
+ case 'left' :
30
+ for ( let i = matrix . length - 1 ; i >= 0 ; i -- ) {
31
+ res . push ( matrix [ i ] . shift ( ) )
32
+ if ( matrix [ i ] . length === 0 ) {
33
+ matrix . splice ( i , 1 )
34
+ }
35
+ }
36
+ dir = 'top'
37
+ break ;
38
+ }
39
+ }
40
+ return res
41
+ } ;
You can’t perform that action at this time.
0 commit comments