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]
提示:
m == matrix.length
n == matrix[i].length
1 <= m, n <= 10
-100 <= matrix[i][j] <= 100
class Solution {
public List<Integer> spiralOrder(int[][] matrix) {
List<Integer> list = new ArrayList<Integer>();
if (matrix == null || matrix.length == 0) return list;
int top = 0, bottom = matrix.length - 1;
int left = 0, right = matrix[0].length - 1;
while (top <= bottom && left <= right) {
// 从左到右遍历
for (int j = left; j <= right; j++) {
list.add(matrix[top][j]);
}
top++;
// 从上到下遍历
for (int i = top; i <= bottom; i++) {
list.add(matrix[i][right]);
}
right--;
// 检查是否顶部越过底部
if (top <= bottom) {
// 从右到左遍历
for (int j = right; j >= left; j--) {
list.add(matrix[bottom][j]);
}
bottom--;
}
// 检查是否左侧越过右侧
if (left <= right) {
// 从下到上遍历
for (int i = bottom; i >= top; i--) {
list.add(matrix[i][left]);
}
left++;
}
}
return list;
}
}