File tree 1 file changed +44
-0
lines changed
1 file changed +44
-0
lines changed Original file line number Diff line number Diff line change
1
+ /**
2
+ * https://leetcode.com/problems/spiral-matrix
3
+ * T.C. O(m * n)
4
+ * S.C. O(m * n)
5
+ */
6
+ function spiralOrder ( matrix : number [ ] [ ] ) : number [ ] {
7
+ const clockwise = [
8
+ [ 0 , 1 ] ,
9
+ [ 1 , 0 ] ,
10
+ [ 0 , - 1 ] ,
11
+ [ - 1 , 0 ] ,
12
+ ] ;
13
+ let currentDirection = 0 ;
14
+
15
+ const visited = new Array ( matrix . length )
16
+ . fill ( 0 )
17
+ . map ( ( ) => new Array ( matrix [ 0 ] . length ) . fill ( false ) ) ;
18
+
19
+ const result : number [ ] = [ ] ;
20
+
21
+ let row = 0 ;
22
+ let col = 0 ;
23
+
24
+ while ( result . length < matrix . length * matrix [ 0 ] . length ) {
25
+ result . push ( matrix [ row ] [ col ] ) ;
26
+ visited [ row ] [ col ] = true ;
27
+
28
+ const nextRow = row + clockwise [ currentDirection ] [ 0 ] ;
29
+ const nextCol = col + clockwise [ currentDirection ] [ 1 ] ;
30
+
31
+ if (
32
+ nextRow < 0 || nextRow >= matrix . length ||
33
+ nextCol < 0 || nextCol >= matrix [ 0 ] . length ||
34
+ visited [ nextRow ] [ nextCol ]
35
+ ) {
36
+ currentDirection = ( currentDirection + 1 ) % 4 ;
37
+ }
38
+
39
+ row += clockwise [ currentDirection ] [ 0 ] ;
40
+ col += clockwise [ currentDirection ] [ 1 ] ;
41
+ }
42
+
43
+ return result ;
44
+ }
You can’t perform that action at this time.
0 commit comments