题目链接:剑指 Offer 29. 顺时针打印矩阵
题目描述:
解法:和蛇形填数差不多思想,进行模拟。定义上下左右四个变量模拟即可,具体见代码。
class Solution {
public int[] spiralOrder(int[][] matrix) {
if (matrix == null || matrix.length == 0 || matrix[0].length == 0) {
return new int[0];
}
int index=0;
int right=matrix[0].length,bottom=matrix.length; //右和下
int left=0,top=0; //左和上
int []res=new int[right*bottom];
right--;
bottom--;
while(left<=right&&top<=bottom){
for(int i=left;i<=right;i++) res[index++]=matrix[top][i]; //左到右
top++;
for(int i=top;i<=bottom;i++) res[index++]=matrix[i][right]; //上到下
right--;
for(int i=right;i>=left&&top<=bottom;i--) res[index++]=matrix[bottom][i]; //右到左
bottom--;
for(int i=bottom;i>=top&&left<=right;i--) res[index++]=matrix[i][left]; //下到上
left++;
}
return res;
}
}