LCR 146题
题目描述:
给定一个二维数组
array
,请返回「螺旋遍历」该数组的结果。螺旋遍历:从左上角开始,按照 向右、向下、向左、向上 的顺序 依次 提取元素,然后再进入内部一层重复相同的步骤,直到提取完所有元素。

**题解思路:**这道题和力扣54题一样题解见https://blog.csdn.net/Miss_croal/article/details/141180630?spm=1001.2014.3001.5502,唯一不一样的就是边界,这个会有 0 的情况,所以一定要把判断放到最前面!
class Solution {
public int[] spiralArray(int[][] array) {
// 样例中有一维空数组,一定要放到最前面来判断!!!否则会显示下标越界
if(array.length == 0) return new int[0];
int m = array.length;
int n = array[0].length;
int[] res = new int[m * n];
int i = 0, j = 0, x = 0, y = 0, index = 0, offset = 1;
int loop = 0;
while (loop < Math.min(m, n) / 2) {
// 向右
for (j = y; j < n - offset; j++) {
res[index++] = array[x][j];
}
// 向下
for (i = x; i < m - offset; i++) {
res[index++] = array[i][j];
}
// 向左
for (; j > y; j--) {
res[index++] = array[i][j];
}
// 向上
for (; i > x; i--) {
res[index++] = array[i][j];
}
// 更新
x++;
y++;
offset++;
loop++;
}
// 判断最后要添加的是中间行还是中间列
if (Math.min(m, n) % 2 == 1) {
if (m > n) {// 添加中间列
for (int t = 0; t < (m - n + 1); t++) {
res[index++] = array[x++][y];
}
} else {// 添加中间行
for (int t = 0; t < (n - m + 1); t++) {
res[index++] = array[x][y++];
}
}
}
return res;
}
}