File tree Expand file tree Collapse file tree 1 file changed +39
-0
lines changed Expand file tree Collapse file tree 1 file changed +39
-0
lines changed Original file line number Diff line number Diff line change
1
+ function spiralOrder ( matrix : number [ ] [ ] ) : number [ ] {
2
+ const rows = matrix . length ;
3
+ const cols = matrix [ 0 ] . length ;
4
+ const total = rows * cols ;
5
+ let srow = 0 ; // start row
6
+ let scol = 0 ;
7
+ let erow = rows - 1 ; // end row
8
+ let ecol = cols - 1 ;
9
+ let count = 0 ;
10
+ const ans : number [ ] = [ ] ;
11
+
12
+ while ( count < total ) {
13
+ for ( let i = scol ; i <= ecol && count < total ; i ++ ) {
14
+ ans . push ( matrix [ srow ] [ i ] ) ;
15
+ count ++ ;
16
+ }
17
+ srow ++ ;
18
+ for ( let i = srow ; i <= erow && count < total ; i ++ ) {
19
+ ans . push ( matrix [ i ] [ ecol ] ) ;
20
+ count ++ ;
21
+ }
22
+ ecol -- ;
23
+ for ( let i = ecol ; i >= scol && count < total ; i -- ) {
24
+ ans . push ( matrix [ erow ] [ i ] ) ;
25
+ count ++ ;
26
+ }
27
+ erow -- ;
28
+ for ( let i = erow ; i >= srow && count < total ; i -- ) {
29
+ ans . push ( matrix [ i ] [ scol ] ) ;
30
+ count ++ ;
31
+ }
32
+ scol ++ ;
33
+ }
34
+
35
+ return ans ;
36
+ }
37
+
38
+ // TC: O(m*n)
39
+ // SC: O(m*n)
You can’t perform that action at this time.
0 commit comments