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
通过次数125,844提交次数278,144
public List<Integer> spiralOrder(int[][] matrix) {
List<Integer> order = new ArrayList<Integer>();
int rows = matrix.length; // 列数
int colums = matrix[0].length; // 行数
int left = 0;
int right = colums-1;
int top = 0;
int bottom = rows-1;
if (matrix==null || rows==0 || colums==0) {
// 刚开始就没有元素,可以直接返回空的表
return order;
}
while (left<=right && top<=bottom) {
for (int colum=left; colum<=right; colum++) {
// 横上
order.add(matrix[left][colum]);
}
for (int row = top + 1; row <= bottom; row++) {
order.add(matrix[row][right]);
}
if (left<right && top<bottom) {
for (int colum=right-1; colum>left; colum--) {
// 下横
order.add(matrix[bottom][colum]);
}
for (int row=bottom; row>top; row--) {
// 有上
order.add(matrix[row][left]);
}
}
left++;
right--;
top++;
bottom--;
}
return order;
}
```