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)

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

相关推荐
郝学胜-神的一滴16 小时前
Effective STL 条款 07:指针容器销毁前先删除
开发语言·c++·vscode·leetcode·rpc·visual studio
CoderYanger16 小时前
A.每日一题:2243. 计算字符串的数字和
java·开发语言·程序人生·leetcode·面试·蓝桥杯·学习方法
青少儿编程课堂19 小时前
蓝桥杯真题解析:三维偏序的CDQ分治(全国青少年信息素养大赛与电子学会编程考级)
c++·python·算法·bfs·信息学竞赛
Navigator_Z19 小时前
LeetCode //C - 1323. Maximum 69 Number
c语言·算法·leetcode
geovindu20 小时前
python:Lasso
开发语言·后端·python·算法
AAA修煤气灶刘哥20 小时前
同一个模型,为什么还要专门练一遍怎么用工具?
人工智能·后端·算法
Severus_black21 小时前
【C++初阶】模板进阶
c语言·c++·学习
AAA修煤气灶刘哥21 小时前
两个 Agent 各自改得都对,合在一起为什么出错?
人工智能·后端·算法
旖旎夜光1 天前
【C 语言】(一)(下)指针进阶:const、二级指针、函数指针与指针题
c语言·开发语言·笔记·学习