54. 螺旋矩阵 - 力扣(LeetCode)

本文详细解析了一种矩阵螺旋遍历算法,通过模拟法实现矩阵元素的顺时针螺旋顺序输出。示例展示了不同大小矩阵的遍历过程,代码采用C++实现,包括方向控制和访问标记,确保了正确性和效率。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目描述

给定一个包含 m x n 个元素的矩阵(m 行, n 列),请按照顺时针螺旋顺序,返回矩阵中的所有元素。
示例 1:
输入:
[
[ 1, 2, 3 ],
[ 4, 5, 6 ],
[ 7, 8, 9 ]
]
输出: [1,2,3,6,9,8,7,4,5]
示例 2:
输入:
[
[1, 2, 3, 4],
[5, 6, 7, 8],
[9,10,11,12]
]
输出: [1,2,3,4,8,12,11,10,9,5,6,7]

题解

模拟法,模拟螺旋矩阵的填写顺序。

代码

/*
模拟法
时间复杂度为o(m * n)
空间复杂度为o(m * n)
*/
class Solution {
public:
    vector<int> spiralOrder(vector<vector<int>>& matrix) {
        int rows = matrix.size();
        if(rows == 0){
            return vector<int>({});
        }
        int cols = matrix[0].size();
        int len = rows * cols, x = 0, y = 0 , idx = 0, next_x, next_y;
        int dir[4][2] = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};//指定螺旋方向
        vector<int>res(rows * cols, 0);
        bool mark[rows][cols];
        memset(mark, false, sizeof(mark));//初始化
        for(int i = 0; i < len; ++i){
            res[i] = matrix[x][y];
            mark[x][y] = true;
            if(i == len - 1) break;
            while(1){
                next_x = x + dir[idx][0];
                next_y = y + dir[idx][1];
                if(next_x < 0 || next_x >= rows || next_y < 0 || next_y >= cols || mark[next_x][next_y]){//越界或者访问过,改变方向
                    idx = (idx + 1) % 4;
                }
                else{//找到螺旋的下一个位置,直接跳出
                    x = next_x;
                    y = next_y;
                    break;
                }
            }
            
        }
        return res;
    }
};

执行结果

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值