给定一个二维数组 array
,请返回「螺旋遍历」该数组的结果。
螺旋遍历:从左上角开始,按照 向右、向下、向左、向上 的顺序 依次 提取元素,然后再进入内部一层重复相同的步骤,直到提取完所有元素。
示例 1:
输入:array = [[1,2,3],[8,9,4],[7,6,5]]
输出:[1,2,3,4,5,6,7,8,9]
示例 2:
输入:array = [[1,2,3,4],[12,13,14,5],[11,16,15,6],[10,9,8,7]]
输出:[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16]
限制:
0 <= array.length <= 100
0 <= array[i].length <= 100
思路:
1、定义四个方位坐标,left、right、top、bottom。
2、从做到右(left->right,++top)、从上到下(top->bottom,--right)、从右到左(right->left,--bottom)、从下到上(botom->top,++left)。
3、每次向结果数组添加元素的时候都让i++,以i小于所有元素个数为条件进行循环螺旋遍历二维数组。
4、返回res数组。
代码实现:
class Solution {
public:
vector<int> spiralArray(vector<vector<int>>& array) {
int row = array.size();
if(row == 0)
return {};
int col = array[0].size();
vector<int>res;
int num = col * row, i = 0;
int left = 0, top = 0, right = col - 1, bottom = row - 1;
while(i < num)
{
for(int j = left; j <= right && i < num; ++j)
{
res.push_back(array[top][j]);
++i;
}
++top;
for(int j = top; j <= bottom && i < num; ++j)
{
res.push_back(array[j][right]);
++i;
}
--right;
for(int j = right; j >= left && i < num; --j)
{
res.push_back(array[bottom][j]);
++i;
}
--bottom;
for(int j = bottom; j >= top && i < num; --j)
{
res.push_back(array[j][left]);
++i;
}
++left;
}
return res;
}
};