LeetCode每日一题——螺旋矩阵

题目要求:

给你一个 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]

代码实现:

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)

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

相关推荐
文丑颜不良啊36 分钟前
LeetCode1461~1480题目解析
java·leetcode
ZhengEnCi9 小时前
Agent 架构怎么选:从单 Agent 到多 Agent 编排的选型决策指南
算法·架构
秋天的怀念_David10 小时前
第二十二夜 · 数字迷雾
java·程序人生·算法
Pniubi10 小时前
力扣283移动零(双指针法)
算法·leetcode·职场和发展
hhb_61811 小时前
大模型落地三重优化实战
人工智能·算法·机器学习
云和数据.ChenGuang11 小时前
光哥说Python RAG 系统需要哪些评估指标:从检索到生成的全链路评测指南
网络·人工智能·python·算法·langchain
2601_9707038312 小时前
工业除湿机租赁:把一份租金合同拆开看
大数据·数据结构·算法·数据库架构·推荐算法
心中有你021412 小时前
Java实现Dijkstra最短路径算法(邻接表 + 优先队列)
java·数据库·算法
ZhengEnCi13 小时前
同样的模型,为什么本地和云 API 差别那么大:量化精度、聊天模板与采样参数的三大元凶
人工智能·算法·llm
Zwawa13 小时前
串口为什么会丢字节:从轮询到中断和环形缓冲区
c语言·单片机·嵌入式