File tree 1 file changed +40
-0
lines changed
1 file changed +40
-0
lines changed Original file line number Diff line number Diff line change
1
+ /*
2
+ * @lc app=leetcode id=54 lang=javascript
3
+ *
4
+ * [54] Spiral Matrix
5
+ */
6
+ /**
7
+ * @param {number[][] } matrix
8
+ * @return {number[] }
9
+ */
10
+ var spiralOrder = function ( matrix ) {
11
+ // https://leetcode.com/problems/spiral-matrix/discuss/20570/Clean-Java-readable-human-friendly-code
12
+ // brilliant!
13
+ const res = [ ] ;
14
+ if ( matrix . length == 0 ) return res ;
15
+
16
+ let top = 0 ;
17
+ let bottom = matrix . length - 1 ;
18
+ let left = 0 ;
19
+ let right = matrix [ 0 ] . length - 1 ;
20
+
21
+ while ( true ) {
22
+ for ( let i = left ; i <= right ; i ++ ) res . push ( matrix [ top ] [ i ] ) ;
23
+ top ++ ;
24
+ if ( top > bottom ) break ;
25
+
26
+ for ( let i = top ; i <= bottom ; i ++ ) res . push ( matrix [ i ] [ right ] ) ;
27
+ right -- ;
28
+ if ( left > right ) break ;
29
+
30
+ for ( let i = right ; i >= left ; i -- ) res . push ( matrix [ bottom ] [ i ] ) ;
31
+ bottom -- ;
32
+ if ( top > bottom ) break ;
33
+
34
+ for ( let i = bottom ; i >= top ; i -- ) res . push ( matrix [ i ] [ left ] ) ;
35
+ left ++ ;
36
+ if ( left > right ) break ;
37
+ }
38
+
39
+ return res ;
40
+ } ;
You can’t perform that action at this time.
0 commit comments