File tree Expand file tree Collapse file tree 1 file changed +45
-0
lines changed Expand file tree Collapse file tree 1 file changed +45
-0
lines changed Original file line number Diff line number Diff line change
1
+ var spiralOrder = function ( matrix ) {
2
+ // Edge case
3
+ if ( matrix . length === 0 ) return [ ] ;
4
+
5
+ let result = [ ] ;
6
+ let rowStart = 0 ,
7
+ rowEnd = matrix . length - 1 ;
8
+ let colStart = 0 ,
9
+ colEnd = matrix [ 0 ] . length - 1 ;
10
+
11
+ while ( rowStart <= rowEnd && colStart <= colEnd ) {
12
+ // Traverse right
13
+ for ( let col = colStart ; col <= colEnd ; col ++ ) {
14
+ result . push ( matrix [ rowStart ] [ col ] ) ;
15
+ }
16
+ rowStart ++ ;
17
+
18
+ // Traverse down
19
+ for ( let row = rowStart ; row <= rowEnd ; row ++ ) {
20
+ result . push ( matrix [ row ] [ colEnd ] ) ;
21
+ }
22
+ colEnd -- ;
23
+
24
+ // Traverse left (check if rowStart <= rowEnd to avoid duplicates)
25
+ if ( rowStart <= rowEnd ) {
26
+ for ( let col = colEnd ; col >= colStart ; col -- ) {
27
+ result . push ( matrix [ rowEnd ] [ col ] ) ;
28
+ }
29
+ rowEnd -- ;
30
+ }
31
+
32
+ // Traverse up (check if colStart <= colEnd to avoid duplicates)
33
+ if ( colStart <= colEnd ) {
34
+ for ( let row = rowEnd ; row >= rowStart ; row -- ) {
35
+ result . push ( matrix [ row ] [ colStart ] ) ;
36
+ }
37
+ colStart ++ ;
38
+ }
39
+ }
40
+
41
+ return result ;
42
+ } ;
43
+
44
+ // TC: O(m*n)
45
+ // SC: O(m*n)
You can’t perform that action at this time.
0 commit comments