标题: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
代码Java
public List<Integer> spiralOrder(int[][] matrix) {
List<Integer> ans = new ArrayList<>();
int top = 0;
int right = matrix[0].length - 1;
int under = matrix.length - 1;
int left = 0;
while (left <= right && top <= under) {
for (int j = left; j <= right; j++) {
ans.add(matrix[top][j]);
}
for (int j = top + 1; j <= under; j++) {
ans.add(matrix[j][right]);
}
if (left < right && top < under) {
for (int j = right - 1; j > left; j--) {
ans.add(matrix[under][j]);
}
for (int j = under; j > top; j--) {
ans.add(matrix[j][left]);
}
}
top++;
right--;
under--;
left++;
}
return ans;
}