Skip to content

Commit 494b036

Browse files
committed
add LeetCode 54. 螺旋矩阵
1 parent 031f2c5 commit 494b036

File tree

1 file changed

+91
-0
lines changed

1 file changed

+91
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,91 @@
1+
![](https://imgconvert.csdnimg.cn/aHR0cHM6Ly9jZG4uanNkZWxpdnIubmV0L2doL2Nob2NvbGF0ZTE5OTkvY2RuL2ltZy8yMDIwMDgyODE0NTUyMS5qcGc?x-oss-process=image/format,png)
2+
>仰望星空的人,不应该被嘲笑
3+
4+
## 题目描述
5+
给定一个包含 m x n 个元素的矩阵(m 行, n 列),请按照顺时针螺旋顺序,返回矩阵中的所有元素。
6+
7+
示例 1:
8+
9+
```css
10+
输入:
11+
[
12+
[ 1, 2, 3 ],
13+
[ 4, 5, 6 ],
14+
[ 7, 8, 9 ]
15+
]
16+
输出: [1,2,3,6,9,8,7,4,5]
17+
```
18+
19+
示例 2:
20+
21+
```css
22+
输入:
23+
[
24+
[1, 2, 3, 4],
25+
[5, 6, 7, 8],
26+
[9,10,11,12]
27+
]
28+
输出: [1,2,3,4,8,12,11,10,9,5,6,7]
29+
```
30+
31+
来源:力扣(LeetCode)
32+
链接:https://leetcode-cn.com/problems/spiral-matrix
33+
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
34+
35+
36+
## 解题思路
37+
38+
和 <a href="https://blog.csdn.net/weixin_42429718/article/details/108535286">上一期</a> 螺旋矩阵差不多,这个是让我么输出,而上次是让我们构造,还是按照螺旋矩阵模拟即可,先从左到右,在从上到下,再从右到左,再从下到上。
39+
40+
不过这里的矩阵行和列不相同了,可能会出现不成环的情况,那么最后会留一列或一行出来,这里借用<a href="https://leetcode-cn.com/problems/spiral-matrix/solution/shou-hui-tu-jie-liang-chong-bian-li-de-ce-lue-kan-/">大佬</a>一张图:
41+
42+
![](https://img-blog.csdnimg.cn/20200911155822316.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3dlaXhpbl80MjQyOTcxOA==,size_16,color_FFFFFF,t_70#pic_center)
43+
然后我们需要提前跳出去一下,就是避免重复计算,总数够了直接跳出去。注意下面代码 `break`。只能放在那里,因为遍历顺序,如果最后留下一行的话,需要从左到右遍历,此时 `top > bottom` 。如果最后留下一列的话,需要从上到下遍历,此时 `left > right`。
44+
45+
```javascript
46+
/**
47+
* @param {number[][]} matrix
48+
* @return {number[]}
49+
*/
50+
var spiralOrder = function(matrix) {
51+
if(!matrix.length) return []
52+
let n = matrix.length
53+
let m = matrix[0].length
54+
let total = n*m
55+
let top = 0,bottom = n-1
56+
let left = 0,right = m-1
57+
let res = []
58+
while(res.length < total){
59+
for(let i=left;i<=right;i++) res.push(matrix[top][i]) // 从左到右
60+
top++
61+
for(let i=top;i<=bottom;i++) res.push(matrix[i][right]) // 从上到下
62+
right--
63+
/* 因为n 和 m 不相同的时候,最后可能会留一列或一行,避免重复计算,总数够了直接跳出去 */
64+
if(res.length === total) break
65+
for(let i=right;i>=left;i--) res.push(matrix[bottom][i]) // 从右到左
66+
bottom--
67+
for(let i=bottom;i>=top;i--) res.push(matrix[i][left]) // 从下到上
68+
left++
69+
}
70+
return res
71+
};
72+
```
73+
74+
75+
76+
## 最后
77+
文章产出不易,还望各位小伙伴们支持一波!
78+
79+
往期精选:
80+
81+
<a href="https://github.com/Chocolate1999/Front-end-learning-to-organize-notes">小狮子前端の笔记仓库</a>
82+
83+
<a href="https://yangchaoyi.vip/">访问超逸の博客</a>,方便小伙伴阅读玩耍~
84+
85+
![](https://img-blog.csdnimg.cn/2020090211491121.png#pic_center)
86+
87+
```javascript
88+
学如逆水行舟,不进则退
89+
```
90+
91+

0 commit comments

Comments
 (0)