LeetCode 54. 螺旋矩阵 (C++实现)

1. 题目描述

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

示例 1:

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

输出:[1,2,3,6,9,8,7,4,5]

示例 2:

输入:matrix = [[1,2,3,4],[5,6,7,8],[9,10,11,12]]

输出:[1,2,3,4,8,12,11,10,9,5,6,7]

2. 解题思路

首先定义左指针left、右指针right,上指针top,下指针bottom,然后从左到右,从上到下遍历,遇到边界的时候指针相应地变化。

3. 代码实现

cpp 复制代码
class Solution {
public:
    vector<int> spiralOrder(vector<vector<int>>& matrix) {
        int left = 0;
        int top = 0;
        int right = matrix[0].size()-1;
        int bottom = matrix.size()-1;
        vector<int> ans;

        while(left <= right || top <= bottom)
        {
            for (int i = left; i <= right; i++)
            {
                ans.push_back(matrix[top][i]);
            }
            top++;
            if (top > bottom) break;
            for (int i = top; i <= bottom; i++)
            {
                ans.push_back(matrix[i][right]);
            }
            right--;
            if (right < left) break;
            for (int i = right; i >= left; i--)
            {
                ans.push_back(matrix[bottom][i]);
            }
            bottom--;
            if (bottom < top) break;
            for (int i = bottom; i >= top; i--)
            {
                ans.push_back(matrix[i][left]);
            }
            left++;
            if (left > right) break;
        }
        return ans;
    }
};
相关推荐
阿巴Jun19 小时前
【数学】线性代数知识点总结
笔记·线性代数·矩阵
利刃大大20 小时前
【高并发内存池】五、页缓存的设计
c++·缓存·项目·内存池
C语言小火车20 小时前
【C++八股文】基础知识篇
c++·tcp/ip·const·智能指针·多线程同步·static关键字·c++内存模型
liulilittle20 小时前
IP校验和算法:从网络协议到SIMD深度优化
网络·c++·网络协议·tcp/ip·算法·ip·通信
眠りたいです21 小时前
基于脚手架微服务的视频点播系统-播放控制部分
c++·qt·ui·微服务·云原生·架构·播放器
Want59521 小时前
C/C++圣诞树①
c语言·开发语言·c++
老赵的博客21 小时前
c++ 杂记
开发语言·c++
jimmy.hua21 小时前
[C++刷怪笼]:set/map--优质且易操作的容器
开发语言·c++
tan180°1 天前
Boost搜索引擎 网络库与前端(4)
linux·网络·c++·搜索引擎
bkspiderx1 天前
C++经典的数据结构与算法之经典算法思想:贪心算法(Greedy)
数据结构·c++·算法·贪心算法