LeetCode 热门100题-螺旋矩阵

题目描述:

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

示例 1:

复制代码
输入:matrix = [[1,2,3],[4,5,6],[7,8,9]]
输出:[1,2,3,6,9,8,7,4,5]

逻辑:

沿着某一边不断访问数组元素,每访问结束一边,就将代表该条边的变量往中心靠拢一次。当访问最底边或者最左边时,进行判断,是否发生触底事件。

cpp 复制代码
class Solution {
public:
    vector<int> spiralOrder(vector<vector<int>>& matrix) {
        vector<int> result;
        if (matrix.empty()) return result;

        int top = 0, bottom = matrix.size() - 1;
        int left = 0, right = matrix[0].size() - 1;

        while (top <= bottom && left <= right) {
            // Traverse from left to right along the top row
            for (int i = left; i <= right; ++i) {
                result.push_back(matrix[top][i]);
            }
            ++top;  // Move down to the next row

            // Traverse from top to bottom along the right column
            for (int i = top; i <= bottom; ++i) {
                result.push_back(matrix[i][right]);
            }
            --right;  // Move left to the next column

            if (top <= bottom) {
                // Traverse from right to left along the bottom row
                for (int i = right; i >= left; --i) {
                    result.push_back(matrix[bottom][i]);
                }
                --bottom;  // Move up to the previous row
            }

            if (left <= right) {
                // Traverse from bottom to top along the left column
                for (int i = bottom; i >= top; --i) {
                    result.push_back(matrix[i][left]);
                }
                ++left;  // Move right to the next column
            }
        }

        return result;
    }
};
相关推荐
lightqjx8 分钟前
【算法】数据结构_单调栈
数据结构·算法·单调栈
Promise微笑10 分钟前
洞察无形:红外热像仪应用场景与高性价比之选
人工智能·物联网·算法
8Qi815 分钟前
LeetCode 746:使用最小花费爬楼梯 —— 题解笔记
java·笔记·算法·leetcode·动态规划
pipo18 分钟前
没雷达也能调 Nav2?我开源了一套仿真到实机复用的 ROS 2 3D LiDAR 导航工作空间
算法
计算机安禾25 分钟前
【算法分析与设计】第44篇:随机化复杂度类:RP、BPP与去随机化猜想
java·数据结构·数据库·算法·机器学习
计算机安禾33 分钟前
【算法分析与设计】第45篇:交互式证明系统与零知识证明
算法·区块链·零知识证明
自进化Agent智能体37 分钟前
Hermes架构全景图:从入口到交付的完整数据流
算法
手写码匠41 分钟前
手写 Prefix Caching:从零构建 LLM 提示词缓存引擎
人工智能·深度学习·算法·aigc
枕星而眠43 分钟前
【数据结构】树与二叉树基础知识点总结
数据结构·c++·后端·算法·运维开发
海梨花43 分钟前
腾讯面试高频算法题
java·算法·面试