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;
    }
};
相关推荐
王老师青少年编程5 小时前
2024年信奥赛C++提高组csp-s初赛真题及答案解析(阅读程序第2题)
c++·题解·真题·初赛·信奥赛·csp-s·提高组
MSTcheng.5 小时前
【C++】C++11新特性(三)
开发语言·c++·c++11
田野追逐星光6 小时前
STL容器list的模拟实现
开发语言·c++·list
TracyCoder1236 小时前
LeetCode Hot100(27/100)——94. 二叉树的中序遍历
算法·leetcode
StandbyTime6 小时前
《算法笔记》学习记录-第二章 C/C++快速入门
c++·算法笔记
深鱼~6 小时前
大模型底层算力支撑:ops-math在矩阵乘法上的优化
人工智能·线性代数·矩阵·cann
我在人间贩卖青春6 小时前
C++之结构体与类
c++··结构体
rainbow68896 小时前
C++实现JSON Web计算器
c++
C++ 老炮儿的技术栈6 小时前
Qt Creator中不写代如何设置 QLabel的颜色
c语言·开发语言·c++·qt·算法
知无不研6 小时前
lambda表达式的原理和由来
java·开发语言·c++·lambda表达式