algorithm-base/animation-simulation/数组篇/leetcode54螺旋矩阵.md

88 lines
3.0 KiB
Java
Raw Normal View History

2021-03-20 08:30:29 +00:00
> **[tan45du_one](https://raw.githubusercontent.com/tan45du/tan45du.github.io/master/个人微信.15egrcgqd94w.jpg)** ,备注 github + 题目 + 问题 向我反馈
>
>
>
> <u>[****](https://raw.githubusercontent.com/tan45du/test/master/微信图片_20210320152235.2pthdebvh1c0.png)</u> 两个平台同步,想要和题友一起刷题,互相监督的同学,可以在我的小屋点击<u>[**刷题小队**](https://raw.githubusercontent.com/tan45du/test/master/微信图片_20210320152235.2pthdebvh1c0.png)</u>进入。
2021-03-20 07:48:03 +00:00
#### [54. ](https://leetcode-cn.com/problems/spiral-matrix/)
2021-03-18 02:05:13 +00:00
* m* x nm , n
> matrix = [[1,2,3],[4,5,6],[7,8,9]]
> [1,2,3,6,9,8,7,4,5]
> matrix = [[1,2,3,4],[5,6,7,8],[9,10,11,12]]
> [1,2,3,4,8,12,11,10,9,5,6,7]
2021-03-20 04:32:33 +00:00
![](https://img-blog.csdnimg.cn/img_convert/cfa0192601dcc185e77125adc35e1cc5.png)*
2021-03-18 02:05:13 +00:00
![](https://img-blog.csdnimg.cn/20210318095839543.gif)
```java
class Solution {
public List<Integer> spiralOrder(int[][] matrix) {
List<Integer> arr = new ArrayList<>();
int left = 0, right = matrix[0].length-1;
int top = 0, down = matrix.length-1;
while (true) {
for (int i = left; i <= right; ++i) {
arr.add(matrix[top][i]);
}
top++;
if (top > down) break;
for (int i = top; i <= down; ++i) {
arr.add(matrix[i][right]);
}
right--;
if (left > right) break;
for (int i = right; i >= left; --i) {
arr.add(matrix[down][i]);
}
down--;
if (top > down) break;
for (int i = down; i >= top; --i) {
arr.add(matrix[i][left]);
}
left++;
if (left > right) break;
}
return arr;
}
}
```