【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)。

相关推荐
小白的高手之路31 分钟前
【【LeetCode 热题 100】160. 相交链表|链表、哈希表、双指针(Python)
python·算法·leetcode·链表·力扣·散列表
程序猿编码32 分钟前
不依赖第三方推理框架:端侧大模型 CUDA 原生推理实现与性能踩坑复盘
c++·llm·大模型推理
草莓熊Lotso44 分钟前
Qt 进阶控件实战:下拉框、列表、表格 + 旋钮 / 滑动条全攻略
大数据·c语言·开发语言·c++·人工智能·qt
会周易的程序员1 小时前
ASX 标准库 API 文档增加标准容器list, queue,map , unordered_map
数据结构·c++·物联网·list·虚拟机·字节码·anglescript
yuki蜜语1 小时前
给大模型配一个"物理传感器":用肚脐椭圆检测,给中医 RAG 加一道可反驳的校验层
算法·计算机视觉·canvas
tong_li2 小时前
给 C++ 后端服务接入企业微信告警:Webhook 原理、架构设计与生产级实现
c++·后端
AAA修煤气灶刘哥2 小时前
明明搜到了同一个故障码,RAG 为什么还会教错你?
算法·llm·agent
龙砚序2 小时前
【数据结构|线性表实战 01】基于顺序表的地铁站点管理:查找、增删、有序二路归并(C 语言实现)
c语言·数据结构·算法
灯澜忆梦2 小时前
拓扑排序(Kahn BFS)| LeetCode 210 课程表 II
算法·leetcode·排序算法·宽度优先
ShineWinsu3 小时前
对于Qt:QMediaPlayer和QVideoWidget的解析
开发语言·c++·qt·视频·客户端·qmediaplayer·媒体播放器