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;
    }
};
相关推荐
小保CPP25 分钟前
OCR C++ Tesseract基础用法
c++·人工智能·ocr·模式识别·光学字符识别
TCW112131 分钟前
AI底层系列:用C++实现线性代数的公式推导与算法设计-8.线性变化(3)
c++·人工智能·算法
ssl_xxy42 分钟前
行列式杂题第二弹
线性代数·矩阵
皓月斯语1 小时前
B3849 [GESP样题 三级] 进制转换 题解
c++·算法·题解
Ljwuhe1 小时前
C++——模板进阶
开发语言·c++
hehelm1 小时前
AI 大模型接入 SDK —项目概述
linux·服务器·网络·数据库·c++
Hesionberger2 小时前
LeetCode406:重建身高队列精髓解析
开发语言·数据结构·python·算法·leetcode
sTone873753 小时前
写时复制COW的第一性理解
android·c++·flutter
卡提西亚3 小时前
leetcode-239. 滑动窗口最大值
算法·leetcode·职场和发展
CHANG_THE_WORLD3 小时前
逐层拆解:C++ 虚函数从对象内存到手工调用的完整过程
java·开发语言·c++