力扣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;
    }
};
相关推荐
星释38 分钟前
Rust 练习册 72:多米诺骨牌与回溯算法
开发语言·算法·rust
算法与编程之美3 小时前
提升minist的准确率并探索分类指标Precision,Recall,F1-Score和Accuracy
人工智能·算法·机器学习·分类·数据挖掘
MicroTech20253 小时前
微算法科技(NASDAQ :MLGO)混合共识算法与机器学习技术:重塑区块链安全新范式
科技·算法·区块链
李牧九丶3 小时前
从零学算法1334
前端·算法
在繁华处3 小时前
C语言经典算法:汉诺塔问题
c语言·算法
le serein —f3 小时前
用go实现-反转链表
leetcode·链表·golang
爪哇部落算法小助手4 小时前
每日两题day50
数据结构·c++·算法
curry____3035 小时前
基本算法(2025.11.21)
c++·算法
WWZZ20256 小时前
快速上手大模型:深度学习5(实践:过、欠拟合)
人工智能·深度学习·神经网络·算法·机器人·大模型·具身智能
司铭鸿6 小时前
图论中的协同寻径:如何找到最小带权子图实现双源共达?
linux·前端·数据结构·数据库·算法·图论