力扣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;
    }
};
相关推荐
haolin123.1 分钟前
STL vector底层揭秘:从构造到迭代器失效
开发语言·c++·算法
shehuiyuelaiyuehao10 分钟前
算法37,位运算,两个整数之和(不用+符号)
算法
猎头南楼16 分钟前
MFC 质量流量控制器中的控制算法设计与落地思考
人工智能·算法
来一碗刘肉面20 分钟前
平衡二叉树的删除
数据结构·算法
wabs66624 分钟前
关于二叉树【力扣199.二叉树的右视图的思考】
数据结构·c++·算法·leetcode·二叉树·层序遍历
a1879272183134 分钟前
【算法】动态规划第三篇:背包第一课——贪心之死与正序倒序开关
算法·leetcode·动态规划·贪心·dp·暴力·算法讲解
黄金龙PLUS43 分钟前
Xoodoo置换算法的优缺点
算法·网络安全·密码学·哈希算法·同态加密
Cccp.1231 小时前
【leetcode】(四)排序算法汇总和链表
leetcode·链表·排序算法
LayZhangStrive1 小时前
数据结构与算法 - 堆排序
java·数据结构·算法·排序算法·堆排序·大根堆
residual_fan2 小时前
深度渐进收缩学习(DPSL):面向强噪声与类内分散的机械复合故障诊断方法
人工智能·算法·数据挖掘·数据分析