Skip to content

Commit 031f2c5

Browse files
committed
add LeetCode 59. 螺旋矩阵 II
1 parent 09c7ce3 commit 031f2c5

File tree

1 file changed

+71
-0
lines changed

1 file changed

+71
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,71 @@
1+
![](https://imgconvert.csdnimg.cn/aHR0cHM6Ly9jZG4uanNkZWxpdnIubmV0L2doL2Nob2NvbGF0ZTE5OTkvY2RuL2ltZy8yMDIwMDgyODE0NTUyMS5qcGc?x-oss-process=image/format,png)
2+
>仰望星空的人,不应该被嘲笑
3+
4+
## 题目描述
5+
给定一个正整数 n,生成一个包含 1 到 n2 所有元素,且元素按顺时针顺序螺旋排列的正方形矩阵。
6+
7+
示例:
8+
9+
```css
10+
输入: 3
11+
输出:
12+
[
13+
[ 1, 2, 3 ],
14+
[ 8, 9, 4 ],
15+
[ 7, 6, 5 ]
16+
]
17+
```
18+
19+
来源:力扣(LeetCode)
20+
链接:https://leetcode-cn.com/problems/spiral-matrix-ii
21+
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
22+
23+
24+
## 解题思路
25+
按照螺旋矩阵模拟即可,先从左到右,在从上到下,再从右到左,再从下到上。
26+
27+
每次进行`cur++`操作,直到累加到`total`为止。最后返回二维数组即可(没想到 `js`二维数组也是这样方便...)
28+
29+
```javascript
30+
/**
31+
* @param {number} n
32+
* @return {number[][]}
33+
*/
34+
var generateMatrix = function(n) {
35+
let top = 0, bottom =n-1
36+
let left = 0, right = n-1
37+
let res = []
38+
for(let i=0;i<n;i++) res[i] = []
39+
let cur = 1, total = n*n
40+
while(cur<=total){
41+
for(let i=left;i<=right;i++) res[top][i] = cur++ // 从左到右
42+
top++
43+
for(let i=top;i<=bottom;i++) res[i][right] = cur++ // 从上到下
44+
right--
45+
for(let i=right;i>=left;i--) res[bottom][i] = cur++ // 从右到左
46+
bottom--
47+
for(let i=bottom;i>=top;i--) res[i][left] = cur++ // 从下到上
48+
left++
49+
}
50+
return res
51+
};
52+
```
53+
54+
55+
56+
## 最后
57+
文章产出不易,还望各位小伙伴们支持一波!
58+
59+
往期精选:
60+
61+
<a href="https://github.com/Chocolate1999/Front-end-learning-to-organize-notes">小狮子前端の笔记仓库</a>
62+
63+
<a href="https://yangchaoyi.vip/">访问超逸の博客</a>,方便小伙伴阅读玩耍~
64+
65+
![](https://img-blog.csdnimg.cn/2020090211491121.png#pic_center)
66+
67+
```javascript
68+
学如逆水行舟,不进则退
69+
```
70+
71+

0 commit comments

Comments
 (0)