力扣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;
    }
};
相关推荐
JJJJ_iii8 分钟前
【机器学习10】项目生命周期、偏斜类别评估、决策树
人工智能·python·深度学习·算法·决策树·机器学习
fie888914 分钟前
基于MATLAB的LBFGS优化算法实现
算法·matlab
天选之女wow15 分钟前
【代码随想录算法训练营——Day50(Day49周日休息)】图论——98.所有可达路径
算法·图论
刀法自然16 分钟前
栈实现表达式求值
数据结构·算法·图论
我搞slam1 小时前
有效的括号--leetcode
linux·算法·leetcode
ゞ 正在缓冲99%…2 小时前
leetcode1312.让字符串成为回文串的最少插入次数
数据结构·算法·leetcode·动态规划·记忆化搜索
七夜zippoe3 小时前
Rust `std::iter` 深度解析:`Iterator` Trait、适配器与性能
开发语言·算法·rust
寂静山林3 小时前
UVa 1464 Traffic Real Time Query System
算法
laocooon5238578863 小时前
寻找使a×b=c成立的最小进制数(2-16进制)
数据结构·算法
YY_TJJ3 小时前
算法题——图论
算法·深度优先·图论