题目
给你一个 m 行 n 列的矩阵 matrix ,请按照 顺时针螺旋顺序 ,返回矩阵中的所有元素。
示例 1:
输入:matrix = [[1,2,3],[4,5,6],[7,8,9]]
输出:[1,2,3,6,9,8,7,4,5]
解
class Solution {
public List<Integer> spiralOrder(int[][] matrix) {
int m = matrix.length;
int n = matrix[0].length;
int len = m * n;
int top = 0;
int bottom = m - 1;
int left = 0;
int right = n - 1;
List<Integer> result = new ArrayList<>();
int j = 0;
while (j < len) {
for (int i = left; i <= right && j < len; i++) {
result.add(matrix[top][i]);
j++;
}
top++;
for (int i = top; i <= bottom && j < len; i++) {
result.add(matrix[i][right]);
j++;
}
right--;
for (int i = right; i >= left && j < len; i--) {
result.add(matrix[bottom][i]);
j++;
}
bottom--;
for (int i = bottom; i >= top && j < len; i--) {
result.add(matrix[i][left]);
j++;
}
left++;
}
return result;
}
}