LCR 146. 螺旋遍历二维数组

本文介绍了一种处理二维数组的螺旋遍历方法,从左上角出发,按右、下、左、上的顺序提取元素,直至遍历完整个数组。提供了C++代码实现,适用于0到1000行、0到100列的矩阵。
摘要由CSDN通过智能技术生成

给定一个二维数组 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;
    }
};
  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值