File tree 2 files changed +45
-0
lines changed
2 files changed +45
-0
lines changed Original file line number Diff line number Diff line change 59
59
54|[ Spiral Matrix] ( ./0054-spiral-matrix.js ) |Medium|
60
60
57|[ Insert Interval] ( ./0057-insert-interval.js ) |Medium|
61
61
58|[ Length of Last Word] ( ./0058-length-of-last-word.js ) |Easy|
62
+ 59|[ Spiral Matrix II] ( ./0059-spiral-matrix-ii.js ) |Medium|
62
63
62|[ Unique Paths] ( ./0062-unique-paths.js ) |Medium|
63
64
66|[ Plus One] ( ./0066-plus-one.js ) |Easy|
64
65
67|[ Add Binary] ( ./0067-add-binary.js ) |Easy|
Original file line number Diff line number Diff line change
1
+ /**
2
+ * 59. Spiral Matrix II
3
+ * https://leetcode.com/problems/spiral-matrix-ii/
4
+ * Difficulty: Medium
5
+ *
6
+ * Given a positive integer n, generate an n x n matrix filled with
7
+ * elements from 1 to n2 in spiral order.
8
+ */
9
+
10
+ /**
11
+ * @param {number } n
12
+ * @return {number[][] }
13
+ */
14
+ var generateMatrix = function ( n ) {
15
+ const result = Array . from ( new Array ( n ) , ( ) => new Array ( n ) . fill ( 0 ) ) ;
16
+ let top = 0 ;
17
+ let right = n - 1 ;
18
+ let bottom = n - 1 ;
19
+ let left = 0 ;
20
+
21
+ for ( let count = 0 ; count < ( n * n ) ; ) {
22
+ for ( let i = left ; i <= right ; i ++ ) {
23
+ result [ top ] [ i ] = ++ count ;
24
+ }
25
+ top ++ ;
26
+
27
+ for ( let i = top ; i <= bottom ; i ++ ) {
28
+ result [ i ] [ right ] = ++ count ;
29
+ }
30
+ right -- ;
31
+
32
+ for ( let i = right ; top <= bottom && i >= left ; i -- ) {
33
+ result [ bottom ] [ i ] = ++ count ;
34
+ }
35
+ bottom -- ;
36
+
37
+ for ( let i = bottom ; left <= right && i >= top ; i -- ) {
38
+ result [ i ] [ left ] = ++ count ;
39
+ }
40
+ left ++ ;
41
+ }
42
+
43
+ return result ;
44
+ } ;
You can’t perform that action at this time.
0 commit comments