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;
    }
};
相关推荐
whoarethenext23 分钟前
C++/OpenCV地砖识别系统结合 Libevent 实现网络化 AI 接入
c++·人工智能·opencv
Antonio91526 分钟前
【Linux】Linux基础I/O
linux·c++
虾球xz34 分钟前
CppCon 2015 学习:C++ devirtualization in clang
开发语言·c++·学习
呆呆的小鳄鱼1 小时前
IO之详解cin(c++IO关键理解)
linux·c语言·c++
爱coding的橙子1 小时前
每日算法刷题Day31 6.14:leetcode二分答案2道题,结束二分答案,开始枚举技巧,用时1h10min
算法·leetcode·职场和发展
看到我,请让我去学习1 小时前
C++核心编程(动态类型转换,STL,Lanmda)
c语言·开发语言·c++·stl
羚羊角uou1 小时前
【C++】模拟实现map和set
java·前端·c++
泽02022 小时前
C++之模板进阶
开发语言·c++·算法
蒙奇D索大2 小时前
【数据结构】图论最短路圣器:Floyd算法如何用双矩阵征服负权图?
数据结构·算法·矩阵·图论·图搜索算法
IC 见路不走4 小时前
LeetCode 第73题:矩阵置零
算法·leetcode·矩阵