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)

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

相关推荐
沐晓时光7 小时前
C语言入门,深入理解指针(3)
c语言·开发语言
信奥卷王7 小时前
[GESP202609 六级] 分树规划
算法
夏幻灵7 小时前
LeetCode 21:合并两个有序链表——双指针与哑节点详解
算法·leetcode·链表
SuperByteMaster8 小时前
wfi进入之前没有清除basepri, 导致中断优先级不够,wfi 退不出来
c语言
徐小黑ACG8 小时前
Golang 基础05 结构体struct
开发语言·算法·golang
Navigator_Z9 小时前
LeetCode //C - 1286. Iterator for Combination
c语言·算法·leetcode
数智工坊9 小时前
视觉SLAM第12讲|地图构建:单目稠密重建、RGB-D点云与八叉树地图全解析
人工智能·深度学习·矩阵·机器人
北极有牛9 小时前
cpp学习笔记--常量指针
java·开发语言·算法
GPU实战笔记9 小时前
云端 GPU 训练的账户余额提醒:它能说明什么,不能说明什么?
深度学习·算法·成本管理·gpu云计算·云端训练