class Solution {
public int[] spiralOrder(int[][] matrix) {
if(matrix == null || matrix.length == 0)return new int[0];
int y = matrix.length; //获取行数
int x = matrix[0].length; //获取列数
int top = 0;
int bottom = y-1;
int left = 0;
int right = x-1;
int[] order = new int[x*y];
int index=0;
while(top <= bottom & left <= right){
for(int clown = left;clown <= right;clown++){
order[index++] = matrix[top][clown];
}
for(int row = top +1;row <= bottom;row++){
order[index++] = matrix[row][right];
}
if(top < bottom & left < right){
for(int clown = right-1;clown > left;clown--){
order[index++] = matrix[bottom][clown];
}
for(int row = bottom; row > top;row--){
order[index++] = matrix[row][left];
}
}
top++;
right--;
left++;
bottom--;
}
return order;
}
}
一层一层遍历,先遍历最外层,然后次外层,.....,定义top,bottom,left,right为每层的顶底左右,遍历完一层后,top+1,bottom-1,left+1,right-1。