力扣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;
    }
};
相关推荐
小竹子148 分钟前
L1-1 天梯赛座位分配
数据结构·c++·算法
董董灿是个攻城狮18 分钟前
Transformer 通关秘籍8:词向量如何表示近义词?
算法
独好紫罗兰40 分钟前
洛谷题单2-P5712 【深基3.例4】Apples-python-流程图重构
开发语言·python·算法
uhakadotcom1 小时前
NVIDIA Resiliency Extension(NVRx)简介:提高PyTorch训练的容错性
算法·面试·github
梭七y1 小时前
【力扣hot100题】(020)搜索二维矩阵Ⅱ
算法·leetcode·职场和发展
v维焓1 小时前
C++(思维导图更新)
开发语言·c++·算法
ylfhpy2 小时前
Java面试黄金宝典22
java·开发语言·算法·面试·职场和发展
Phoebe鑫2 小时前
数据结构每日一题day9(顺序表)★★★★★
数据结构·算法
烁3472 小时前
每日一题(小白)动态规划篇2
算法·动态规划
南玖yy3 小时前
数据结构C语言练习(栈)
c语言·数据结构·算法