给定一个包含 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) {
List<Integer> res=new LinkedList<Integer>();
if(matrix.length==0){
return res;
}
int startCol=0; //起始列位置
int startRow=0; //起始行位置
int endRow=matrix.length-1; //终止行位置
int endCol=matrix[0].length-1; //终止列位置
while(true){
//top
for (int j=startCol;j<=endCol;j++){
res.add(matrix[startRow][j]);
}
startRow++;
if(startRow>endRow) break;
//right
for (int i=startRow;i<=endRow;i++){
res.add(matrix[i][endCol]);
}
endCol--;
if(startCol>endCol) break;
//down
for (int j=endCol;j>=startCol;j--){
res.add(matrix[endRow][j]);
}
endRow--;
if(startRow>endRow) break;
//left
for (int i=endRow;i>=startRow;i--){
res.add(matrix[i][startCol]);
}
startCol++;
if(startCol>endCol) {
break;
}
}
return res;
}
}