LeetCode每日一题——螺旋矩阵

题目要求:

给你一个 mn 列的矩阵 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]

代码实现:

int directions42 = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};//作为方向偏移量

int* spiralOrder(int** matrix, int matrixSize, int* matrixColSize, int* returnSize) {

if (matrixSize == 0 || matrixColSize0 == 0) {//包含矩阵无元素的情况

*returnSize = 0;

return NULL;

}

int rows = matrixSize, columns = matrixColSize0;//分别表示矩阵的行数和列数

int visitedrowscolumns;//用来标记元素是否被访问

memset(visited, 0, sizeof(visited));

int total = rows * columns;

int* order = malloc(sizeof(int) * total);

*returnSize = total;

int row = 0, column = 0;

int directionIndex = 0;//作为方向索引

for (int i = 0; i < total; i++) {

orderi = matrixrowcolumn;

visitedrowcolumn = true;//访问完标记该位置

int nextRow = row + directionsdirectionIndex0, nextColumn = column + directionsdirectionIndex1;

if (nextRow < 0 || nextRow >= rows || nextColumn < 0 || nextColumn >= columns || visitednextRownextColumn) {

directionIndex = (directionIndex + 1) % 4;//控制directionIndex在0~3之间,继续下一个循环

}

row += directionsdirectionIndex0;//更新行

column += directionsdirectionIndex1;//更新列

}

return order;//返回最终结果

}

作者:力扣官方题解

来源:力扣(LeetCode)

坚持编程,我一直在路上!

相关推荐
单片机仿真设计30 分钟前
【proteus仿真】基于 STM32 的智能垃圾桶设计(仿真图+程序)
c语言·stm32·stm32单片机·proteus·毕设·仿真
kaixin_啊啊40 分钟前
专用优化算法LKH
算法
_Narcissus_2 小时前
二分算法笔记及例题
数据结构·c++·笔记·算法·蓝桥杯·查找·二分算法
tachibana22 小时前
RAGAS 指标解读
数据库·人工智能·算法·机器学习·架构·大模型·llm
qq_419563093 小时前
ToT 的 BFS/DFS 有个致命缺口:蒙特卡洛树搜索(MCTS)用「随机试错+统计」让大模型想得更深,小模型 + 它竟超过 GPT-4
算法·深度优先·宽度优先
万法若空4 小时前
CSP-J/S 排序算法完整专题训练题单
数据结构·算法·排序算法
凉茶钱4 小时前
【数据结构】排序(快排,选择,直接插入,希尔)
数据结构·算法·排序算法
weixin_446260854 小时前
拆解再复用:大模型智能体的跨任务技能迁移
人工智能·深度学习·算法
Brilliantwxx4 小时前
【Linux】 进程(4)七大进程状态深度解析
linux·运维·算法
青少儿编程课堂4 小时前
用图形化编程做一个“少年探险闯关”小游戏:方向键控制、碰撞检测与多关卡串起完整项目
c++·python·算法·bfs·信息学竞赛