力扣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;
    }
};
相关推荐
历程里程碑11 分钟前
LeetCode 560题:和为K子数组最优解
算法·哈希算法·散列表
qq_4017004127 分钟前
C/C++中的signed char和unsigned char详解
c语言·c++·算法
leoufung40 分钟前
LeetCode 67. Add Binary:从面试思路到代码细节
算法·leetcode·面试
无限进步_1 小时前
【C语言】循环队列的两种实现:数组与链表的对比分析
c语言·开发语言·数据结构·c++·leetcode·链表·visual studio
wjykp1 小时前
79~87逻辑回归f
算法·机器学习·逻辑回归
聆风吟º1 小时前
【顺序表习题|图解|双指针】合并两个有序数组 + 训练计划 I
c语言·数据结构·c++·经验分享·算法
wa的一声哭了1 小时前
矩阵分析 方阵幂级数与方阵函数
人工智能·python·线性代数·算法·自然语言处理·矩阵·django
菩提祖师_1 小时前
基于MATLAB的心电信号处理与心律异常检测算法设计
算法·matlab·信号处理
foundbug9991 小时前
用ode45求解悬臂梁的动力学方程,得到其变形
算法
linsa_pursuer1 小时前
最长连续序列
java·数据结构·算法·leetcode