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;
    }
};
相关推荐
Wenhao.4 小时前
LeetCode 救生艇
算法·leetcode·golang
夏鹏今天学习了吗4 小时前
【LeetCode热题100(69/100)】字符串解码
linux·算法·leetcode
普通网友5 小时前
内存对齐与缓存友好设计
开发语言·c++·算法
小白程序员成长日记5 小时前
2025.11.18 力扣每日一题
算法·leetcode·职场和发展
普通网友5 小时前
C++编译期数据结构
开发语言·c++·算法
代码程序猿RIP5 小时前
【C++开发面经】全过程面试问题详解
java·c++·面试
普通网友6 小时前
嵌入式C++安全编码
开发语言·c++·算法
云知谷6 小时前
【软件测试】《集成测试全攻略:Mock/Stub 原理 + Postman/JUnit/TestNG 实战》
c语言·开发语言·c++·软件工程·团队开发
普通网友6 小时前
分布式锁服务实现
开发语言·c++·算法
普通网友6 小时前
移动语义在容器中的应用
开发语言·c++·算法