题目描述:
输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字。
例如:
输入:matrix = [[1,2,3],[4,5,6],[7,8,9]]
输出:[1,2,3,6,9,8,7,4,5]
参考代码:
public int[] spiralOrder(int[][] matrix) {
if(matrix == null || matrix.length == 0)return new int[]{};
int left = 0;
int right = matrix[0].length - 1;
int top = 0;
int bottom = matrix.length - 1;
int [] res = new int[(right + 1) * (bottom+ 1)];
int x = 0;
while(true){
for(int i = left; i <= right; i ++)res[x ++] = matrix[top][i];
if(++ top > bottom)break;
for(int i = top; i <= bottom; i ++)res[x ++] = matrix[i][right];
if(-- right < left)break;
for(int i = right; i >= left; i --)res[x ++] = matrix[bottom][i];
if(-- bottom < top)break;
for(int i = bottom; i >= top; i --)res[x ++] = matrix[i][left];
if(++ left > right)break;
}
return res;
}
(完)