class Solution {
public int[] spiralOrder(int[][] matrix) {
if (matrix.length == 0) {
return new int[]{};
}
int[] arr = new int[matrix.length * matrix[0].length];
int top = 0;
int bottom = matrix.length - 1;
int left = 0;
int right = matrix[0].length - 1;
int j = 0;
while (top < (matrix.length + 1) / 2 && left < (matrix[0].length + 1) / 2) {
for (int i = left; i <= right; i++){
arr[j] = matrix[top][i];
j++;
}
for (int i = top + 1; i <= bottom; i++) {
arr[j] = matrix[i][right];
j++;
}
for (int i = right - 1; i >= left && top != bottom; i--) {
arr[j] = matrix[bottom][i];
j++;
}
for (int i = bottom - 1; i >= top + 1 && left != right; i--) {
arr[j] = matrix[i][left];
j++;
}
++top;
--bottom;
++left;
--right;
}
return arr;
}
}
注意数组的大小,注意判空