力扣54. 螺旋矩阵

Problem: 54. 螺旋矩阵

文章目录

题目描述

思路

定义四个标志top、bottom、left、right标记矩阵的四个方位,依次**从左到右(执行后top++);从上到下(执行后right--);从右到左(执行后bottom--);从左到右(执行后left++)**螺旋遍历并将元素添加到一个二维数组中

复杂度

时间复杂度:

O ( M × N ) O(M \times N) O(M×N);其中 M M M是矩阵的行数 N N N为矩阵的列数

空间复杂度:

O ( M × N ) O(M \times N) O(M×N)

Code

cpp 复制代码
class Solution {
public:
    /**
     * 
     * @param matrix Given matrix 
     * @return vector<int>
     */
    vector<int> spiralOrder(vector<vector<int>>& matrix) {
        int row = matrix.size();
        int col = matrix[0].size();
        int top = 0;
        int bottom = row - 1;
        int left = 0;
        int right = col - 1;
        vector<int> res;
        while (left <= right && top <= bottom) {
            //From left to right
            for (int i = left; i <= right; ++i) {
                res.push_back(matrix[top][i]);
            }
            top++;
            //From top to bottom
            for (int i = top; i <= bottom; ++i) {
                res.push_back(matrix[i][right]);
            }
            right--;
            //From right to left
            for (int i = right; (i >= left && top <= bottom); --i) {
                res.push_back(matrix[bottom][i]);
            }
            bottom--;
            //From bottom to top
            for (int i = bottom; (i >= top && left <= right); --i) {
                res.push_back(matrix[i][left]);
            }
            left++;
        }
        return res;
    }
};
相关推荐
拳里剑气4 小时前
C++算法:BFS解决FloodFill算法
c++·算法·bfs·宽度优先
wanderist.6 小时前
Lambda表达式在算法竞赛中的应用
java·开发语言·算法
稚南城才子,乌衣巷风流6 小时前
支配树(Dominator Tree)详解:概念、算法与应用
算法
稚南城才子,乌衣巷风流7 小时前
动态开点:原理、实现与应用场景
数据结构·算法
yyds_yyd_100867 小时前
1464. 数组中两元素的最大乘积(2026.07.27)
数据结构·c++·算法·leetcode
KaMeidebaby8 小时前
卡梅德生物技术快报 | 核酸适配体文库测序:核酸适配体文库测序的技术原理、实验流程与数据解析
前端·网络·数据库·人工智能·算法
geovindu9 小时前
CSharp: Breadth First Search Algorithm and Depth First Search Algorithm
开发语言·后端·算法·c#·.net·搜索算法
ekkoalex10 小时前
训练框架以及算法实现的框架
算法
DFT计算杂谈10 小时前
交错磁研究进展材料物性与交叉应用
数据库·人工智能·python·opencv·算法