LeetCode 54:螺旋矩阵
题目
给你一个 m 行 n 列的矩阵 matrix ,请按照 顺时针螺旋顺序 ,返回矩阵中的所有元素。
示例 1:
输入:matrix = [[1,2,3],[4,5,6],[7,8,9]]
输出:[1,2,3,6,9,8,7,4,5]
示例 2:
输入: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]
思路
设置四个边界,对应四个方向
代码
class Solution {
public List<Integer> spiralOrder(int[][] matrix) {
List<Integer> res=new ArrayList<>();
int m=matrix.length;
int n=matrix[0].length;
int up = 0, down = m - 1, left = 0, right = n - 1;
while (true)
{
for (int i = left; i <= right; i++)
res.add(matrix[up][i]);
if (++up > down) break;
for (int i = up; i <= down; i++)
res.add(matrix[i][right]);
if (--right < left) break;
for (int i = right; i >= left; i--)
res.add(matrix[down][i]);
if (--down < up) break;
for (int i = down; i >= up; i--)
res.add(matrix[i][left]);
if (++left > right) break;
}
return res;
}
}
反思
①最好把图画出来
标签:matrix,int,54,矩阵,up,down,res,LeetCode,left From: https://www.cnblogs.com/Janecodehouse/p/17039885.html