力扣54-螺旋矩阵-C++

一、题目

给你一个 m 行 n 列的矩阵 matrix ,请按照 顺时针螺旋顺序 ,返回矩阵中的所有元素。

示例 1:
输入:matrix = [[1,2,3],[4,5,6],[7,8,9]]
输出:[1,2,3,6,9,8,7,4,5]

 

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/spiral-matrix

二、解题思路

        用四个变量作为四个方向的边界,沿着矩阵边界进行顺时针遍历,每遍历一条边界上的数据,对应的边界就往中间进行收缩,直至其中两个方向的边界相等,遍历结束。

三、程序

class Solution {
public:
    vector<int> spiralOrder(vector<vector<int>>& matrix) {
        int len1 = matrix.size();
        int len2 = matrix[0].size();
        vector<int> ans;
        int top = 0, left = 0, right = len2 -1, bottom = len1  -1;  //控制四条边界
        while(top <= bottom && left <= right){ 
            int ltor = left;
            while(ltor <= right){  //上边 左→右
                ans.push_back(matrix[top][ltor]);
                ltor++;
            }
            top++;
            if(top > bottom) break;
            int ttob = top;
            while(ttob <= bottom){  //右边 上→下
                ans.push_back(matrix[ttob][right]);
                ttob++;
            }
            right--;
            if(right < left) break;
            int rtol = right;
            while(rtol >= left){  //下边 右→左
                ans.push_back(matrix[bottom][rtol]);
                rtol--;
            }
            bottom--;
            if(bottom < top) break;
            int btot = bottom;
            while(btot >= top){  //左边 下→上
                ans.push_back(matrix[btot][left]);
                btot--;
            }
            left++;
        }
        return ans;
    }
};

四、运行结果

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值