LeetCode 54. 螺旋矩阵 (C++实现)

1. 题目描述

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

示例 1:

输入:matrix = [[1,2,3],[4,5,6],[7,8,9]]

输出:[1,2,3,6,9,8,7,4,5]

示例 2:

输入:matrix = [[1,2,3,4],[5,6,7,8],[9,10,11,12]]

输出:[1,2,3,4,8,12,11,10,9,5,6,7]

2. 解题思路

首先定义左指针left、右指针right,上指针top,下指针bottom,然后从左到右,从上到下遍历,遇到边界的时候指针相应地变化。

3. 代码实现

cpp 复制代码
class Solution {
public:
    vector<int> spiralOrder(vector<vector<int>>& matrix) {
        int left = 0;
        int top = 0;
        int right = matrix[0].size()-1;
        int bottom = matrix.size()-1;
        vector<int> ans;

        while(left <= right || top <= bottom)
        {
            for (int i = left; i <= right; i++)
            {
                ans.push_back(matrix[top][i]);
            }
            top++;
            if (top > bottom) break;
            for (int i = top; i <= bottom; i++)
            {
                ans.push_back(matrix[i][right]);
            }
            right--;
            if (right < left) break;
            for (int i = right; i >= left; i--)
            {
                ans.push_back(matrix[bottom][i]);
            }
            bottom--;
            if (bottom < top) break;
            for (int i = bottom; i >= top; i--)
            {
                ans.push_back(matrix[i][left]);
            }
            left++;
            if (left > right) break;
        }
        return ans;
    }
};
相关推荐
浮灯Foden2 小时前
算法-每日一题(DAY13)两数之和
开发语言·数据结构·c++·算法·leetcode·面试·散列表
淡海水2 小时前
【原理】Struct 和 Class 辨析
开发语言·c++·c#·struct·class
执子手 吹散苍茫茫烟波4 小时前
leetcode415. 字符串相加
java·leetcode·字符串
青草地溪水旁4 小时前
UML函数原型中stereotype的含义,有啥用?
c++·uml
青草地溪水旁4 小时前
UML函数原型中guard的含义,有啥用?
c++·uml
执子手 吹散苍茫茫烟波5 小时前
LCR 076. 数组中的第 K 个最大元素
leetcode·排序算法
山顶风景独好6 小时前
【Leetcode】随笔
数据结构·算法·leetcode
光头闪亮亮6 小时前
C++凡人修仙法典 - 宗门版-上
c++
光头闪亮亮7 小时前
C++凡人修仙法典 - 宗门版-下
c++
John_ToDebug7 小时前
Chromium base 库中的 Observer 模式实现:ObserverList 与 ObserverListThreadSafe 深度解析
c++·chrome·性能优化