根据题意,需要特判,对于空矩阵直接返回空数组。
定义出二维数组的左右上下四个边界,left、right、top、bottom;
循环打印:
- 沿着top,从左向右打印,top++;
- 沿着right,从上向下打印,right--;
- 沿着bottom,从右向左打印,bottom++;
- 沿着left,从下向上打印,left++;
注:在沿着下边界和左边界打印时,要确保left <= right,top <= bottom。
public int[] spiralOrder(int[][] matrix) {
if(matrix == null || matrix.length == 0){
return new int[0];
}
//定义四个边界
int left = 0;
int right = matrix[0].length-1;
int top = 0;
int bottom = matrix.length-1;
//记录元素
int[] res = new int[matrix.length * matrix[0].length];
int k = 0;
while( left <= right && top <= bottom){
//从左到右打印
for(int i = left; i <= right; i++){
res[k++] = matrix[top][i];
}
top++;
//从上到下打印
for(int i = top; i <= bottom; i++){
res[k++] = matrix[i][right];
}
right--;
//从右到左打印
for(int i = right; i >= left && top <= bottom; i--){
res[k++] = matrix[bottom][i];
}
bottom--;
//从下到上打印
for(int i = bottom; i >= top && left <= right; i--){
res[k++] = matrix[i][left];
}
left++;
}
return res;
}