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

相关推荐
zephyr055 分钟前
C++ STL unordered_set 与 unordered_map 完全指南
开发语言·数据结构·c++
wen__xvn8 分钟前
牛客周赛 Round 127
算法
大锦终10 分钟前
dfs解决FloodFill 算法
c++·算法·深度优先
一只小bit17 分钟前
Qt 事件:覆盖介绍、处理、各种类型及运用全详解
前端·c++·qt·cpp
追烽少年x20 分钟前
第三章 异常(一)
c++
橘颂TA23 分钟前
【剑斩OFFER】算法的暴力美学——LeetCode 200 题:岛屿数量
算法·leetcode·职场和发展
苦藤新鸡26 分钟前
14.合并区间(1,3)(2,5)=(1,5)
c++·算法·leetcode·动态规划
程序员-King.36 分钟前
day145—递归—二叉树的右视图(LeetCode-199)
算法·leetcode·二叉树·递归
漫随流水40 分钟前
leetcode算法(112.路径总和)
数据结构·算法·leetcode·二叉树
过期的秋刀鱼!1 小时前
机器学习-带正则化的成本函数-
人工智能·python·深度学习·算法·机器学习·逻辑回归