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

150 lines
4.7 KiB
Java
Raw Blame History

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

> **[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>进入。
### [59. II](https://leetcode-cn.com/problems/spiral-matrix-ii)
`n` `1` `n2` `n x n` `matrix`
** 1**
> n = 3
> [[1,2,3],[8,9,4],[7,6,5]]
** 2**
> n = 1
> [[1]]
**leetcode 54**
### leetcode 54
* 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]
*![](https://pic.leetcode-cn.com/1615813563-uUiWlF-file_1615813563382)*
![](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;
}
}
```
54 ,
```java
class Solution {
public int[][] generateMatrix(int n) {
int[][] arr = new int[n][n];
int left = 0;
int right = n-1;
int top = 0;
int buttom = n-1;
int num = 1;
int numsize = n*n;
while (true) {
for (int i = left; i <= right; ++i) {
arr[top][i] = num++;
}
top++;
if (num > numsize) break;
for (int i = top; i <= buttom; ++i) {
arr[i][right] = num++;
}
right--;
if (num > numsize) break;
for (int i = right; i >= left; --i) {
arr[buttom][i] = num++;
}
buttom--;
if (num > numsize) break;
for (int i = buttom; i >= top; --i) {
arr[i][left] = num++;
}
left++;
if (num > numsize) break;
}
return arr;
}
}
```