leetcode 54. 螺旋矩阵

题目要求

在这里插入图片描述

解题思路

按照题目描述字面意思,从矩阵最外层开始向内层顺时针遍历。
两层循环嵌套,外层循环控制层数,内层循环遍历每层元素。

  • 判断边界条件
  • 通过左上角(top,left)和右下角(bottom,right)坐标位置限制每层的遍历范围
  • 每层遍历
    • 顶边:(top,left -> right),顶边的所有元素
    • 右边:(top + 1 -> bottom,right),右边除第一个元素外所有元素
    • 底边:(bottom,right - 1 -> left),底边除最右侧元素外所有元素
    • 左边:(bottom - 1 -> top - 1,left),左边除第一个和最后一个元素外所有元素

代码

class Solution {
public:
    vector<int> spiralOrder(vector<vector<int>>& matrix) {
        if (matrix.size() == 0 || matrix[0].size() == 0)
        {
            return {};
        }
        vector<int> res;
        int rows = matrix.size();
        int cols = matrix[0].size();
        int left = 0, right = cols - 1;
        int top = 0, bottom = rows - 1;
        while (left <= right && top <= bottom)
        {
            for (int j = left; j <= right; ++j)
            {
                res.push_back(matrix[top][j]);
            }
            for (int i = top + 1; i <= bottom; ++i)
            {
                res.push_back(matrix[i][right]);
            }
            if (left < right && top < bottom)
            {
                for (int j = right - 1; j >= left; --j)
                {
                    res.push_back(matrix[bottom][j]);
                }
                for (int i = bottom - 1; i > top; --i)
                {
                    res.push_back(matrix[i][left]);
                }
            }
            left++;
            right--;
            top++;
            bottom--;
        }
        return res;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值