题目
给定一个包含 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]
解题思路
详细思路请参考 面试题29. 顺时针打印矩阵
代码
class Solution {
public List<Integer> spiralOrder(int[][] matrix) {
List<Integer> res = new ArrayList<Integer>();
if(matrix == null || matrix.length == 0 || matrix[0].length == 0){
return res;
}
int m = matrix.length;
int n = matrix[0].length;
int top = 0, left = 0;
int bottom = m-1, right = n-1;
while(top <= bottom && left <= right){
// 从左到右
for(int j=left; j<=right; j++){
res.add(matrix[top][j]);
}
// 从上到下
if(top<bottom){
for(int i=top+1; i<= bottom; i++){
res.add(matrix[i][right]);
}
}
// 从右到左
if(top<bottom && left<right){
for(int j=right-1; j>=left; j--){
res.add(matrix[bottom][j]);
}
}
// 从下到上
if(top<bottom-1 && left<right){
for(int i=bottom-1; i>=top+1; i--){
res.add(matrix[i][left]);
}
}
top++;
left++;
bottom--;
right--;
}
return res;
}
}