File tree 1 file changed +23
-43
lines changed
1 file changed +23
-43
lines changed Original file line number Diff line number Diff line change 1
1
/**
2
2
* 59. 螺旋矩阵 II
3
+ * 参考: https://leetcode.cn/problems/spiral-matrix-ii/solution/spiral-matrix-ii-mo-ni-fa-she-ding-bian-jie-qing-x/
3
4
* @param {number } n
4
5
* @return {number[][] }
5
6
*/
6
- var generateMatrix = function ( n ) {
7
- // 矩阵的行列索引
8
- let i , j ;
9
- // 起始位置
10
- let startX = 0 , startY = 0 ;
11
- // 旋转圈数
12
- let loop = n >> 1 ;
13
- // 中间位置
14
- let mid = loop ;
15
- // 控制每一条边遍历的长度,每次循环右边界收缩一位
16
- let offset = 1 ;
17
- // 填充矩阵的值
18
- let count = 1 ;
19
- // 结果矩阵
20
- let nums = Array . from ( { length : n } , ( ) => [ ] ) ;
7
+ var generateMatrix = function ( n ) {
8
+ let cur = 1 ;
9
+ let top = 0 ;
10
+ let bottom = n - 1 ;
11
+ let left = 0 ;
12
+ let right = n - 1 ;
13
+ const tar = n * n ;
21
14
22
- while ( loop -- ) {
23
- // 上行从左到右(左闭右开)
24
- for ( j = startX ; j < n - offset ; j ++ ) {
25
- nums [ startX ] [ j ] = count ++ ;
26
- }
27
- // 右列从上到下(左闭右开)
28
- for ( i = startY ; i < n - offset ; i ++ ) {
29
- nums [ i ] [ j ] = count ++ ;
30
- }
31
- // 下行从右到左(左闭右开)
32
- for ( ; j > startY ; j -- ) {
33
- nums [ i ] [ j ] = count ++ ;
34
- }
35
- // 左列从下到上(左闭右开)
36
- for ( ; i > startX ; i -- ) {
37
- nums [ i ] [ j ] = count ++ ;
38
- }
39
- // 更新起始位置
40
- startX ++ ;
41
- startY ++ ;
42
- // offset 控制每一圈里每一条边遍历的长度
43
- offset ++ ;
44
- }
45
- // n 为奇数, 处理中间的值
46
- if ( n % 2 === 1 ) {
47
- nums [ mid ] [ mid ] = count ;
15
+ const mat = Array ( n )
16
+ . fill ( 0 )
17
+ . map ( ( ) => Array ( n ) . fill ( 0 ) ) ;
18
+
19
+ while ( cur <= tar ) {
20
+ for ( let i = left ; i <= right ; i ++ ) mat [ top ] [ i ] = cur ++ ;
21
+ top ++ ;
22
+ for ( let i = top ; i <= bottom ; i ++ ) mat [ i ] [ right ] = cur ++ ;
23
+ right -- ;
24
+ for ( let i = right ; i >= left ; i -- ) mat [ bottom ] [ i ] = cur ++ ;
25
+ bottom -- ;
26
+ for ( let i = bottom ; i >= top ; i -- ) mat [ i ] [ left ] = cur ++ ;
27
+ left ++ ;
48
28
}
49
29
50
- return nums ;
51
- } ;
30
+ return mat ;
31
+ } ;
You can’t perform that action at this time.
0 commit comments