File tree Expand file tree Collapse file tree 1 file changed +40
-0
lines changed
Expand file tree Collapse file tree 1 file changed +40
-0
lines changed Original file line number Diff line number Diff line change 1+ function spiralOrder ( matrix : number [ ] [ ] ) : number [ ] {
2+ let x = 0 ;
3+ let y = 0 ;
4+
5+ let result : number [ ] = [ ] ;
6+ const threshold = matrix . length * matrix [ 0 ] . length
7+
8+ let direction = 0 ;
9+ const dx = [ 0 , 1 , 0 , - 1 ] ;
10+ const dy = [ 1 , 0 , - 1 , 0 ] ;
11+ let visited = Array . from ( { length : matrix . length } , ( ) => Array ( matrix [ 0 ] . length ) . fill ( false ) )
12+
13+ while ( true ) {
14+ if ( result . length >= threshold ) {
15+ break ;
16+ }
17+
18+ result . push ( matrix [ x ] [ y ] ) ;
19+ visited [ x ] [ y ] = true
20+
21+ const nx = x + dx [ direction ]
22+ const ny = y + dy [ direction ]
23+
24+ if ( nx < 0 || nx >= matrix . length || ny < 0 || ny >= matrix [ 0 ] . length || visited [ nx ] [ ny ] ) {
25+ direction ++ ;
26+
27+ if ( direction > 3 ) {
28+ direction = 0 ;
29+ }
30+
31+ x += dx [ direction ] ;
32+ y += dy [ direction ] ;
33+ } else {
34+ x = nx ;
35+ y = ny ;
36+ }
37+ }
38+
39+ return result ;
40+ } ;
You can’t perform that action at this time.
0 commit comments