题目描述
给定一个包含 m x n 个元素的矩阵(m 行, n 列),请按照顺时针螺旋顺序,返回矩阵中的所有元素。
示例 1:
输入:
[
[ 1, 2, 3 ],
[ 4, 5, 6 ],
[ 7, 8, 9 ]
]
输出: [1,2,3,6,9,8,7,4,5]
示例 2:
输入:
[
[1, 2, 3, 4],
[5, 6, 7, 8],
[9,10,11,12]
]
输出: [1,2,3,4,8,12,11,10,9,5,6,7]
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/spiral-matrix
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
白话题目:
算法:
详细解释关注 B站 【C语言全代码】学渣带你刷Leetcode 不走丢 https://www.bilibili.com/video/BV1C7411y7gB
C语言完全代码
/**
* Note: The returned array must be malloced, assume caller calls free().
*/
int* spiralOrder(int** matrix, int matrixSize, int* matrixColSize, int* returnSize)
{
if(matrixSize==0){
*returnSize=0;
return NULL;
}
int *result=(int *)malloc(sizeof(int)*(matrixSize*(*matrixColSize)));
int c=0;
int up=0,down=matrixSize-1,left=0,right=*matrixColSize-1;
while(up<=down&&left<=right){
for(int i=left;i<=right;i++){
result[c++]=matrix[up][i];
}
up++;
if(up>down){
break;
}
for(int i=up;i<=down;i++){
result[c++]=matrix[i][right];
}
right--;
if(left>right){
break;
}
for(int i=right;i>=left;i--){
result[c++]=matrix[down][i];
}
down--;
if(up>down){
break;
}
for(int i=down;i>=up;i--){
result[c++]=matrix[i][left];
}
left++;
if(left>right){
break;
}
}
*returnSize=c;
return result;
}