54.螺旋矩阵
标签:数组、矩阵、模拟
难度:中等
描述:给定一个 m×n 大小的二维矩阵 matrix。
要求:按照顺时针旋转的顺序,返回矩阵中的所有元素。
说明:
m==matrix.length。
n==matrix[i].length。
1≤m,n≤10。
−100≤matrix[i][j]≤100。
示例:
示例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]思路
定义上下左右数组访问的边界,分别用top、bottom、left、right表示。
按照从左到右、从上到下、从右到左、从下到上的顺序依次遍历。
从左到右访问数组之后,顶部已经遍历完了,上边界top+1。然后判断top是否大于下边界bottom,如果top超过bottom,说明数组元素都已经遍历完了,结束循环。
从上到下访问数组之后,右部已经遍历完了,右边界right+1。其余类似。
从右到左访问数组之后,底部已经遍历完了,下边界bottom+1。其余类似。
从下到上访问数组之后,左部已经遍历完了,左边界left+1。其余类似。

public List<Integer> spiralOrder(int[][] matrix) {
int m = matrix.length;
int n = matrix[0].length;
// 定义上下左右边界
int left = 0, top = 0;
int right = n - 1, bottom = m - 1;
List<Integer> res = new ArrayList<>();
// i,j用于遍历位置的行、列坐标
int i = 0, j = 0;
if (matrix == null || m == 0 || n == 0) {
return res;
}
while (true){
// 从左到右
for (j = left; j <= right; j++){
res.add(matrix[top][j]);
}
if (++top > bottom)
break;
// 从上到下
for (i = top; i <= bottom; i++){
res.add(matrix[i][right]);
}
if (--right < left)
break;
// 从右到左
for (j = right; j >= left; j--){
res.add(matrix[bottom][j]);
}
if (--bottom < top)
break;
// 从下到上
for (i = bottom; i >= top; i--){
res.add(matrix[i][left]);
}
if (++left > right)
break;
}
return res;
}
评论区