给你一个 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]
/**
* Note: The returned array must be malloced, assume caller calls free().
*/
int *spiralOrder(int **matrix, int matrixSize, int *matrixColSize, int *returnSize)
{
int rows = matrixSize, columns = matrixColSize[0];
int total = rows * columns;
int *order = malloc(sizeof(int) * total);
*returnSize = 0;
// 对变量进行抽象,可大大减小指针操作复杂度
int left = 0, right = columns - 1, top = 0, bottom = rows - 1;
while (left <= right && top <= bottom)
{
for (int column = left; column <= right; column++)
{
order[(*returnSize)++] = *(*(matrix + top) + column);
printf("%d\n", *(*(matrix + top) + column));
}
for (int row = top + 1; row <= bottom; row++)
{
order[(*returnSize)++] = *(*(matrix + row) + right);
printf("%d\n", *(*(matrix + row) + right));
}
if (left < right && top < bottom)
{
for (int column = right - 1; column > left; column--)
{
order[(*returnSize)++] = *(*(matrix + bottom) + column);
}
for (int row = bottom; row > top ; row--)
{
order[(*returnSize)++] = *(*(matrix + row) + left);
}
}
left++;
right--;
top++;
bottom--;
}
return order;
}
原文:https://www.cnblogs.com/yangtai/p/14851188.html