力扣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;
    }
};
相关推荐
和风化雨13 分钟前
排序算法--计数排序
c语言·数据结构·c++·算法·排序算法
MiyamiKK572 小时前
leetcode_双指针 160.相交链表
算法·leetcode·链表
迪小莫学AI2 小时前
LeetCode 2909. 元素和最小的山形三元组 II
算法·leetcode·职场和发展
阿巴~阿巴~3 小时前
C_数据结构(队列) —— 队列的初始化、入队列队尾、队列判空、出队列队头、取队头队尾数据、队列有效元素个数、销毁队列
c语言·网络·数据结构·算法·排序算法
Lenyiin3 小时前
2848、与车相交的点
c++·算法·leetcode·1024程序员节
mljy.3 小时前
优选算法《前缀和》
c++·算法
小林熬夜学编程4 小时前
【MySQL】第一弹---MySQL 在 Centos 7环境安装
linux·开发语言·数据库·mysql·算法
魂兮-龙游4 小时前
C语言:将四个八位无符号数据拼接成32位的float数据
c语言·开发语言·算法·数据分析
self-discipline3625 小时前
2025.2.5总结
数据结构·算法
银河梦想家6 小时前
【Day31 LeetCode】动态规划DP Ⅳ
算法·leetcode·动态规划