leetcode 54. 螺旋矩阵(Spiral Matrix)

本文详细解析了一种矩阵螺旋遍历算法,该算法能够按照顺时针螺旋顺序返回矩阵中的所有元素。通过实例展示了算法的具体实现过程,包括输入为不同大小的矩阵时的输出结果。适用于需要对二维数据进行特定顺序访问的场景。

摘要生成于 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]

解法:

class Solution {
public:
    vector<int> spiralOrder(vector<vector<int>>& matrix) {
        int x = 0, y = 0;
        bool right = true, down = false, left = false, up = false;
        
        int dx = 0, dy = 1;
        
        vector<int> res;
        int m = matrix.size();
        if(m == 0){
            return res;
        }else if(m == 1){
            return matrix[0];
        }
        int n = matrix[0].size();
        if(n == 0){
            return res;
        }else if(n == 1){
            for(vector<int> lst : matrix){
                res.push_back(lst[0]);
            }
            return res;
        }
        int idx = m*n;
        int min_x = 1, max_x = m-1;
        int min_y = 0, max_y = n-1;
        while(idx--){
            res.push_back(matrix[x][y]);
            x += dx;
            y += dy;
            if(right && y == max_y){
                right = false;
                down = true;
                dx = 1;
                dy = 0;
                max_y--;
            }else if(down && x == max_x){
                down = false;
                left = true;
                dx = 0;
                dy = -1;
                max_x--;
            }else if(left && y == min_y){
                left = false;
                up = true;
                dx = -1;
                dy = 0;
                min_y++;
            }else if(up && x == min_x){
                up = false;
                right = true;
                dx = 0;
                dy = 1;
                min_x++;
            }
        }
        return res;
    }
};

转载于:https://www.cnblogs.com/zhanzq/p/10715452.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值