【C++】每日一题 54 螺旋矩阵

给你一个 m 行 n 列的矩阵 matrix ,请按照 顺时针螺旋顺序 ,返回矩阵中的所有元素。

示例 1:

输入:matrix = [[1,2,3],[4,5,6],[7,8,9]]

输出:[1,2,3,6,9,8,7,4,5]

cpp 复制代码
#include <iostream>
#include <vector>

using namespace std;

vector<int> spiralOrder(vector<vector<int>>& matrix) {
    vector<int> result;
    if (matrix.empty()) return result;
    
    int m = matrix.size(); // 行数
    int n = matrix[0].size(); // 列数
    int top = 0, bottom = m - 1, left = 0, right = n - 1;
    
    while (top <= bottom && left <= right) {
        // Traverse right
        for (int i = left; i <= right; ++i) {
            result.push_back(matrix[top][i]);
        }
        ++top;
        
        // Traverse down
        for (int i = top; i <= bottom; ++i) {
            result.push_back(matrix[i][right]);
        }
        --right;
        
        // Traverse left
        if (top <= bottom) {
            for (int i = right; i >= left; --i) {
                result.push_back(matrix[bottom][i]);
            }
            --bottom;
        }
        
        // Traverse up
        if (left <= right) {
            for (int i = bottom; i >= top; --i) {
                result.push_back(matrix[i][left]);
            }
            ++left;
        }
    }
    
    return result;
}

int main() {
    vector<vector<int>> matrix = {
        {1, 2, 3},
        {4, 5, 6},
        {7, 8, 9}
    };
    
    vector<int> result = spiralOrder(matrix);
    
    // 输出结果
    for (int num : result) {
        cout << num << " ";
    }
    cout << endl;
    
    return 0;
}

模拟螺旋遍历的过程。通过维护四个边界来确定当前遍历的范围,然后依次按照顺时针的方向遍历矩阵,将元素添加到结果数组中。

时间复杂度分析:

遍历整个矩阵需要访问每个元素一次,因此时间复杂度为 O(m * n),其中 m 是矩阵的行数,n 是矩阵的列数。

空间复杂度分析:

除了存储结果的数组外,算法的空间复杂度主要取决于额外的变量和常数大小的空间。因此,空间复杂度为 O(1)。

相关推荐
水木流年追梦12 分钟前
大模型入门-应用篇3-Agent智能体
开发语言·python·算法·leetcode·正则表达式
洛水水21 分钟前
【力扣100题】31.二叉树的层序遍历
算法·leetcode·职场和发展
君义_noip27 分钟前
CSP-S 2025 入门级 第一轮(初赛) 完善程序(1)
c++·算法·信息学奥赛·初赛·csp 第一轮
洛水水30 分钟前
【力扣100题】41.爬楼梯
算法·leetcode·职场和发展
蜡笔小马2 小时前
07.C++设计模式-组合模式
c++·设计模式·组合模式
sheeta19982 小时前
LeetCode 每日一题笔记 日期:2026.05.13 题目:1674. 使数组互补的最少操作次数
笔记·算法·leetcode
liulilittle2 小时前
TCP UCP v1.0:BBR 的非破坏性约束层
网络·c++·网络协议·tcp/ip·算法·c·通信
每天回答3个问题2 小时前
LeetCodeHot100|回溯算法、46.全排列、78.子集、17.电话号码的字母组合
算法·深度优先·回溯
每天回答3个问题2 小时前
leetcodeHot100 | 104.二叉树的最大深度
c++·面试·
坚果派·白晓明2 小时前
【鸿蒙PC三方库移植适配框架解读系列】第五篇:完整流程图与角色职责
c语言·c++·华为·harmonyos·鸿蒙