59题目:
给你一个正整数 n
,生成一个包含 1
到 n2
所有元素,且元素按顺时针顺序螺旋排列的 n x n
正方形矩阵 matrix
。
示例 1:
输入:n = 3 输出:[[1,2,3],[8,9,4],[7,6,5]]
示例 2:
输入:n = 1 输出:[[1]]
思路:一个n*n的数组,需要循环n/2个圈,每一圈我们需要循环四条边,每条边按照左开右闭的原理去给二维数组赋值。如果n/2等于奇数,就是剩下最中间的一个点,单独进行赋值
C语言
int** generateMatrix(int n, int* returnSize, int** returnColumnSizes)
{
*returnSize=n;
*returnColumnSizes=(int*)malloc(sizeof(int) * n);
int** array = (int**)malloc(sizeof(int*) * n);
for(int i=0;i<n;i++)
{
array[i]=(int*)malloc(sizeof(int)*n);
(*returnColumnSizes)[i] = n;
}
int start_x=0;
int start_y=0;
int circle=1;
int count=1;
int i=0;
int j=0;
int loop=n/2;
while(loop>=0)
{
for (j=start_y;j<n-circle;j++)
{
array[start_x][j]=count;
count++;
}
for(i=start_x;i<n-circle;i++)
{
array[i][j]=count;
count++;
}
for(j;j>start_y;j--)
{
array[i][j]=count;
count++;
}
for(i;i>start_x;i--)
{
array[i][j]=count;
count++;
}
start_x++;
start_y++;
circle++;
loop--;
}
if (n%2==1)
{
array[i][j]=count;
}
return array;
}
python 语言
class Solution(object):
def generateMatrix(self, n):
"""
:type n: int
:rtype: List[List[int]]
"""
start_x=0
start_y=0
circle=1
count=1
array=[[0 for x in range(n)]for j in range(n)]
loop=n/2
while loop>=0:
i=start_x
j=start_y
while j<n-circle:
array[start_x][j]=count
count+=1
j+=1
while i<n-circle:
array[i][j]=count
count+=1
i+=1
while j>start_y:
array[i][j]=count
count+=1
j-=1
while i>start_x:
array[i][j]=count
count+=1
i-=1
start_x+=1
start_y+=1
circle+=1
loop-=1
if n%2==1:
array[i][j]=count
return array