LeetCode 热门100题-螺旋矩阵

题目描述:

给你一个 mn 列的矩阵 matrix ,请按照 顺时针螺旋顺序 ,返回矩阵中的所有元素。

示例 1:

复制代码
输入:matrix = [[1,2,3],[4,5,6],[7,8,9]]
输出:[1,2,3,6,9,8,7,4,5]

逻辑:

沿着某一边不断访问数组元素,每访问结束一边,就将代表该条边的变量往中心靠拢一次。当访问最底边或者最左边时,进行判断,是否发生触底事件。

cpp 复制代码
class Solution {
public:
    vector<int> spiralOrder(vector<vector<int>>& matrix) {
        vector<int> result;
        if (matrix.empty()) return result;

        int top = 0, bottom = matrix.size() - 1;
        int left = 0, right = matrix[0].size() - 1;

        while (top <= bottom && left <= right) {
            // Traverse from left to right along the top row
            for (int i = left; i <= right; ++i) {
                result.push_back(matrix[top][i]);
            }
            ++top;  // Move down to the next row

            // Traverse from top to bottom along the right column
            for (int i = top; i <= bottom; ++i) {
                result.push_back(matrix[i][right]);
            }
            --right;  // Move left to the next column

            if (top <= bottom) {
                // Traverse from right to left along the bottom row
                for (int i = right; i >= left; --i) {
                    result.push_back(matrix[bottom][i]);
                }
                --bottom;  // Move up to the previous row
            }

            if (left <= right) {
                // Traverse from bottom to top along the left column
                for (int i = bottom; i >= top; --i) {
                    result.push_back(matrix[i][left]);
                }
                ++left;  // Move right to the next column
            }
        }

        return result;
    }
};
相关推荐
乱次序_Chaos35 分钟前
【监督学习】线性回归算法步骤及matlab实现
学习·算法·matlab·线性回归
TAK_AGI1 小时前
Day29 第八章 贪心算法 part02
算法·贪心算法
是Yu欸1 小时前
【博资考1】网安学院-北航网安数学基础部分
经验分享·笔记·算法·决策树·机器学习·论文笔记
原来是猿2 小时前
蓝桥备赛(四)- 数组(下)
开发语言·数据结构·c++·算法
ephemerals__2 小时前
【数据结构进阶】哈希表
数据结构·算法·散列表
阿巴~阿巴~2 小时前
关于回溯算法中的剪枝是否需要for循环的总结归纳
数据结构·c++·算法·深度优先·剪枝
一只_程序媛3 小时前
【leetcode hot 100 42】接雨水
java·算法·leetcode
普通young man3 小时前
哈希封装unordered_map/unordered_set
算法·哈希算法
Dovis(誓平步青云)3 小时前
【数据结构】二叉树(门槛极低的系统理解)
c语言·数据结构·算法
朔北之忘 Clancy3 小时前
2022 年 12 月青少年软编等考 C 语言五级真题解析
c语言·开发语言·c++·学习·算法·青少年编程·题解