LeetCode 热门100题-螺旋矩阵

题目描述:

给你一个 m 行 n 列的矩阵 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;
    }
};
相关推荐
而后笑面对37 分钟前
浅尝贝叶斯估计
人工智能·算法·机器学习
u0111026752 小时前
图片生成任务的日志记录与敏感信息取舍
前端·图像处理·算法·ai作画
花间相见2 小时前
【计算基础|MySQL08】索引(上):为什么是 B+ 树
数据结构·mysql·算法·架构
吠品2 小时前
Flutter 工程配本地 Maven 引 AAR,仓库声明为啥不生效
c语言·人工智能·算法
罗湖老棍子2 小时前
【例题1】黑暗城堡(信息学奥赛一本通- P1486)
算法·图论·最短路·dijkstra·最小生成树·最短路径生成树
hetao17338373 小时前
2026-10-20 hetao1733837 的刷题记录
c++·算法
wenyq73 小时前
LeetCode 123. Best Time to Buy and Sell Stock III
leetcode
碧海银沙音频科技研究院4 小时前
基于ATS308X的无线语音交互对话功能实现
人工智能·嵌入式硬件·深度学习·算法
I Am a robert girl5 小时前
MeqMuon 源码级拆解:当优化器开始“配平”更新矩阵
深度学习·线性代数·矩阵·优化器·大模型预训练·muon·矩阵正交化