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;
    }
};
相关推荐
2401_891482174 小时前
多平台UI框架C++开发
开发语言·c++·算法
88号技师4 小时前
2026年3月中科院一区SCI-贝塞尔曲线优化算法Bezier curve-based optimization-附Matlab免费代码
开发语言·算法·matlab·优化算法
t198751284 小时前
三维点云最小二乘拟合MATLAB程序
开发语言·算法·matlab
无敌昊哥战神4 小时前
【LeetCode 257】二叉树的所有路径(回溯法/深度优先遍历)- Python/C/C++详细题解
c语言·c++·python·leetcode·深度优先
x_xbx5 小时前
LeetCode:148. 排序链表
算法·leetcode·链表
Darkwanderor5 小时前
三分算法的简单应用
c++·算法·三分法·三分算法
2401_831920745 小时前
分布式系统安全通信
开发语言·c++·算法
WolfGang0073216 小时前
代码随想录算法训练营 Day17 | 二叉树 part07
算法
温九味闻醉6 小时前
关于腾讯广告算法大赛2025项目分析1 - dataset.py
人工智能·算法·机器学习
炽烈小老头6 小时前
【 每天学习一点算法 2026/03/23】数组中的第K个最大元素
学习·算法·排序算法