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;
    }
};
相关推荐
广州灵眸科技有限公司3 分钟前
瑞芯微(EASY EAI)RV1126B openclaw部署接入飞书
linux·网络·人工智能·算法·yolo·飞书
工业机器人销售服务5 分钟前
告别漫长停机:伯朗特机器人如何用“自动换模”重塑生产效率
大数据·人工智能·算法
listhi52011 分钟前
LTE标准下Turbo码编译码仿真
算法·matlab
吞下星星的少年·-·19 分钟前
区间转化、扫描线
算法
笨笨饿30 分钟前
80_聊聊SPI以及它们的变体
linux·c语言·网络·stm32·单片机·算法·个人开发
Ricardo-Yang31 分钟前
使用GEE以及LandSat8植被指数NDVI计算
python·深度学习·神经网络·算法·视觉检测
sheeta199836 分钟前
LeetCode 每日一题笔记 日期:2026.05.12 题目:1665. 完成所有任务的最少初始能量
笔记·算法·leetcode
khalil102037 分钟前
代码随想录算法训练营Day-49 图论01 | 图论理论基础、深搜理论基础、98. 所有可达路径、广搜理论基础
c++·算法·leetcode·深度优先·图论
Chase_______1 小时前
【算法】删除子数组的最大得分 & 最多 K 个重复元素的最长子数组——不定长滑动窗口与哈希频率约束
算法·哈希算法
森屿~~1 小时前
CMA-ES:从搜索分布自适应到协方差矩阵学习
学习·elasticsearch·矩阵