LeetCode 热门100题-螺旋矩阵

devtools/2025/2/28 12:08:29/

题目描述:

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

示例 1:

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

 逻辑:

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

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 rowfor (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 columnfor (int i = top; i <= bottom; ++i) {result.push_back(matrix[i][right]);}--right;  // Move left to the next columnif (top <= bottom) {// Traverse from right to left along the bottom rowfor (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 columnfor (int i = bottom; i >= top; --i) {result.push_back(matrix[i][left]);}++left;  // Move right to the next column}}return result;}
};


http://www.ppmy.cn/devtools/163338.html

相关文章

使用Python爬虫获取京东商品评论API接口的详细指南

在数据分析和市场研究中&#xff0c;商品评论数据是了解用户需求和产品改进方向的重要资源。京东作为国内知名的电商平台&#xff0c;提供了丰富的商品评论数据接口&#xff08;JD.item_review&#xff09;&#xff0c;开发者可以通过这些接口获取商品评论的详细信息&#xff0…

基于coze+微信小程序的ai对话

界面介绍&#xff1a; 代码&#xff1a;&#xff08;替换你的coze的配置&#xff09; <template><view class"container"><!-- 高斯模糊背景 --><view class"animated-bg"><view class"gradient-blob"></view…

Lua语言入门(自用)

全局与非全局 在lua语言当中没有被local表示的是全局变量 反之则是本地变量(仅仅作用在某个文件,函数,或者代码块) 下面是实例代码和运行结果 --hello.luaA 10;--这样就是全局变量,然后这个编译器如果是大写就是默认的全局变量 local b 3;--这样就是局部变量--reference.…

使用Docker Desktop部署GitLab

1. 环境准备 确保Windows 10/11系统支持虚拟化技术&#xff08;需在BIOS中开启Intel VT-x/AMD-V&#xff09;内存建议≥8GB&#xff0c;存储空间≥100GB 2. 安装Docker Desktop 访问Docker官网下载安装包安装时勾选"Use WSL 2 instead of Hyper-V"&#xff08;推荐…

【RAG 优化实战】query改写提升复杂语义的搜索精度

RAG 通过结合大型语言模型 (LLM) 的生成能力和外部知识库的检索能力,能够生成更准确、更可靠、更具信息量的响应。然而,当用户查询包含多个语义或较为复杂时,RAG 系统的检索效果往往会受到影响。查询改写 (Query Rewriting) 作为一种有效的优化手段,可以通过将复杂查询转化…

react中,在组件内返回style标签方法

方法1 var styles变量其实可以写在组件外 方法2

父子继承与转型

ISettings为接口&#xff0c;Settings是实现类。 1、Settings可以自动转型为ISettings&#xff1b; 2、List<Settings>不可以自动转型为List<ISettings>&#xff0c; 原因在于泛型类型在 Java 中是 不可协变&#xff08;invariant&#xff09;的&#xff0c;即使…

【二分查找 图论】P8794 [蓝桥杯 2022 国 A] 环境治理|普及

本文涉及的基础知识点 本博文代码打包下载 C二分查找 C图论 [蓝桥杯 2022 国 A] 环境治理 题目描述 LQ 国拥有 n n n 个城市&#xff0c;从 0 0 0 到 n − 1 n - 1 n−1 编号&#xff0c;这 n n n 个城市两两之间都有且仅有一条双向道路连接&#xff0c;这意味着任意两…