題目描述
給定一個正整數 n,生成一個包含 1 到 n2 所有元素,且元素按順時針順序螺旋排列的正方形矩陣。
示例:
輸入: 3
輸出:
[
[ 1, 2, 3 ],
[ 8, 9, 4 ],
[ 7, 6, 5 ]
]
來源:力扣(LeetCode)
鏈接:https://leetcode-cn.com/problems/spiral-matrix-ii
著作權歸領釦網絡所有。商業轉載請聯繫官方授權,非商業轉載請註明出處。
白話題目:
算法:
詳細解釋關注 B站 【C語言全代碼】學渣帶你刷Leetcode 不走丟 https://www.bilibili.com/video/BV1C7411y7gB
C語言完全代碼
/**
* Return an array of arrays of size *returnSize.
* The sizes of the arrays are returned as *returnColumnSizes array.
* Note: Both returned array and *columnSizes array must be malloced, assume caller calls free().
*/
enum Direction
{
up = 0,
right,
down,
left,
};
int** generateMatrix(int n, int* returnSize, int** returnColumnSizes){
if (n <= 0)
{
*returnSize = 0;
*returnColumnSizes = (int*)malloc(1 * sizeof(int));
(*returnColumnSizes)[*returnSize] = 0;
return NULL;
}
enum Direction direction = 0; // LeetCode平臺定義全局變量會報錯,因此這裏定義枚舉類型
int uiTop = 0;
int uiRight = n - 1;
int uiBottom = n - 1;
int uiLeft = 0;
int index = 0;
int num = 0;
int** ppRes = (int**)malloc(n * n * sizeof(int*));
for (index = 0; index <= n - 1; index++)
{
ppRes[index] = (int*)malloc(n * sizeof(int));
}
*returnSize = n;
*returnColumnSizes = (int*)malloc(n * sizeof(int));
for (index = 0; index <= n - 1; index++)
{
(*returnColumnSizes)[index] = n;
}
while (num < n * n)
{
switch (direction)
{
case up:
{
for (index = uiLeft; index <= uiRight; index++)
{
ppRes[uiTop][index] = ++num;
}
uiTop++;
break;
}
case right:
{
for (index = uiTop; index <= uiBottom; index++)
{
ppRes[index][uiRight] = ++num;
}
uiRight--;
break;
}
case down:
{
for (index = uiRight; index >= uiLeft; index--)
{
ppRes[uiBottom][index] = ++num;
}
uiBottom--;
break;
}
case left:
{
for (index = uiBottom; index >= uiTop; index--)
{
ppRes[index][uiLeft] = ++num;
}
uiLeft++;
break;
}
default:
break;
}
direction = (++direction) % 4;
}
return ppRes;
}