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
+ var spiralOrder = function ( matrix ) {
6
+ if ( matrix . length === 0 ) return [ ] ;
7
+
8
+ const result = [ ] ;
9
+ const rows = matrix . length ;
10
+ const cols = matrix [ 0 ] . length ;
11
+
12
+ let top = 0 , bottom = rows - 1 , left = 0 , right = cols - 1 ;
13
+
14
+ while ( top <= bottom && left <= right ) {
15
+ for ( let i = left ; i <= right ; i ++ ) {
16
+ result . push ( matrix [ top ] [ i ] ) ;
17
+ }
18
+ top += 1 ;
19
+
20
+ for ( let i = top ; i <= bottom ; i ++ ) {
21
+ result . push ( matrix [ i ] [ right ] ) ;
22
+ }
23
+ right -= 1 ;
24
+
25
+ if ( top <= bottom ) {
26
+ for ( let i = right ; i >= left ; i -- ) {
27
+ result . push ( matrix [ bottom ] [ i ] ) ;
28
+ }
29
+ bottom -= 1 ;
30
+ }
31
+
32
+ if ( left <= right ) {
33
+ for ( let i = bottom ; i >= top ; i -- ) {
34
+ result . push ( matrix [ i ] [ left ] ) ;
35
+ }
36
+ left += 1 ;
37
+ }
38
+ }
39
+
40
+ return result ;
41
+ } ;
You can’t perform that action at this time.
0 commit comments