1. 题目描述
给你一个 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]
提示:
m == matrix.length
n == matrix[i].length
1 <= m, n <= 10
-100 <= matrix[i][j] <= 100
通过次数106,548提交次数247,391
2.代码如下
int* spiralOrder(int** matrix, int matrixSize, int* matrixColSize, int* returnSize)
{
int size = matrixSize*(*matrixColSize);
int *ret = (int *)malloc(sizeof(int)*size);
memset(ret,0,sizeof(int)*size);
int i = 0;
int up = 0;
int down = matrixSize - 1;
int left = 0;
int right = *matrixColSize - 1;
*returnSize = 0;
while (1)
{
// ---->
for (i = left;i <= right;i++)
{
ret[*returnSize] = matrix[up][i];
*returnSize += 1;
}
up += 1;
if (up > down)
{
break;
}
// \|/
for (i = up;i<= down;i++)
{
ret[*returnSize] = matrix[i][right];
*returnSize += 1;
}
right -= 1;
if (left > right)
{
break;
}
// <----
for (i=right;i>=left;i--)
{
ret[*returnSize] = matrix[down][i];
*returnSize += 1;
}
down -=1;
if (up > down)
{
break;
}
// /|\
for (i=down;i>=up;i--)
{
ret[*returnSize] = matrix[i][left];
*returnSize += 1;
}
left += 1;
if (left > right)
{
break;
}
}
return ret;
}