给定一个包含 m x n 个元素的矩阵(m 行, n 列),请按照顺时针螺旋顺序,返回矩阵中的所有元素。
示例 1:
输入:
[
[ 1, 2, 3 ],
[ 4, 5, 6 ],
[ 7, 8, 9 ]
]
输出: [1,2,3,6,9,8,7,4,5]
示例 2:
输入:
[
[1, 2, 3, 4],
[5, 6, 7, 8],
[9,10,11,12]
]
输出: [1,2,3,4,8,12,11,10,9,5,6,7]
题解
class Solution {
public List<Integer> spiralOrder(int[][] matrix) {
if (matrix.length == 0) {
return new ArrayList<>(0);
}
int M = matrix.length;
int N = matrix[0].length;
List<Integer> list = new ArrayList<>(M * N);
int i,j;
int p = M, q = N;
int m = 0;
while(p>0 && q>0) {
i = m; j= m;
while(j<=N-m-1) list.add(matrix[i][j++]);
i = i+1; j = N-m-1;
while(i<=M-m-1) list.add(matrix[i++][j]);
i = M-m-1; j=j-1;
while(i>m && j>=m) list.add(matrix[i][j--]);
i = i-1; j=m;
while(i>m && j<N-m-1) list.add(matrix[i--][j]);
m++;
p-=2;
q-=2;
}
return list;
}
}