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

相关推荐
罗超驿14 小时前
14.LeetCode 438 题解:滑动窗口+哈希表找所有字母异位词
java·算法·leetcode
白驹笙鸣14 小时前
STL allocator作用
开发语言·c++
小小编程路14 小时前
C++ STL 原理与性能
开发语言·c++
小欣加油14 小时前
leetcode239 滑动窗口最大值
数据结构·c++·算法·leetcode·哈希算法
luoganttcc14 小时前
FP16 和 BF16 的数学表达
算法
玖釉-14 小时前
Vulkan 示例解析:pipelines.cpp 如何在一个 Render Pass 中切换多条 Graphics Pipeline
c++·windows·算法·图形渲染
ji1985944315 小时前
局部线性嵌入(LLE)算法 MATLAB 实现
算法·机器学习·matlab
Deepoch15 小时前
Deepoc VLA开发板:无人机群体协同与无网络自主作业核心
网络·人工智能·算法·无人机·deepoc·具身模型开发板
hai31524754315 小时前
# 矩阵算法·算子对齐工具 v6.1 — 技术规格与使用手册
java·开发语言·驱动开发·神经网络·spring·目标检测·矩阵
随意起个昵称15 小时前
线性dp-计数类题目11(不等数列)
c++·算法·动态规划