題目
給定一個包含 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;
}
}