题目
输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字。
代码实现
模拟
class Solution {
public int[] spiralOrder(int[][] matrix) {
if (matrix.length == 0){
return new int[]{};
}
int m = matrix.length;
int n = matrix[0].length;
int[] res = new int[m * n];
int index = 0;
int left = 0,right = n-1,top = 0,bottom = m-1;
while (true){
//从左到右
for (int i = left; i <= right; i++) {
res[index++] = matrix[top][i];
}
//如果当前top行已经是bottom行了,则退出
if (++top > bottom){
break;
}
//从上到下
for (int i = top; i <= bottom; i++) {
res[index++] = matrix[i][right];
}
//如果当前right列已经是left的列,则退出
if(--right < left){
break;
}
//从右到左
for (int i = right; i >= left; i--) {
res[index++] = matrix[bottom][i];
}
//如果当前bottom行已经是top行
if(--bottom < top){
break;
}
//从下到上
for (int i = bottom; i >= top; i--) {
res[index++] = matrix[i][left];
}
//如果当前left列已经是right列,则退出
if(++left > right){
break;
}
}
return res;
}
}