Skip to content

Commit e23549c

Browse files
committed
59. 螺旋矩阵 II
1 parent 35afb4d commit e23549c

File tree

2 files changed

+52
-0
lines changed

2 files changed

+52
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,7 @@
3333
|48|[旋转图像](https://leetcode.cn/problems/rotate-image/)|[JavaScript](./algorithms/rotate-image.js)|Medium|
3434
|49|[字母异位词分组](https://leetcode.cn/problems/group-anagrams/)|[JavaScript](./algorithms/group-anagrams.js)|Medium|
3535
|58|[最后一个单词的长度](https://leetcode.cn/problems/length-of-last-word/)|[JavaScript](./algorithms/length-of-last-word.js)|Easy|
36+
|59|[螺旋矩阵 II](https://leetcode.cn/problems/spiral-matrix-ii/)|[JavaScript](./algorithms/spiral-matrix-ii.js)|Medium|
3637
|53|[最大子数组和](https://leetcode.cn/problems/maximum-subarray/)|[JavaScript](./algorithms/maximum-subarray.js)|Easy|
3738
|66|[加一](https://leetcode-cn.com/problems/plus-one/)|[JavaScript](./algorithms/plus-one.js)|Easy|
3839
|69|[x 的平方根 ](https://leetcode.cn/problems/sqrtx/)|[JavaScript](./algorithms/sqrtx.js)|Easy|

algorithms/spiral-matrix-ii.js

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
/**
2+
* 59. 螺旋矩阵 II
3+
* @param {number} n
4+
* @return {number[][]}
5+
*/
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 }, () => []);
21+
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;
48+
}
49+
50+
return nums;
51+
};

0 commit comments

Comments
 (0)