给定一个正整数 n,生成一个包含 1 到 n2 所有元素,且元素按顺时针顺序螺旋排列的正方形矩阵。
示例:
输入: 3
输出:
[
[ 1, 2, 3 ],
[ 8, 9, 4 ],
[ 7, 6, 5 ]
]
C
/**
* Return an array of arrays.
* Note: The returned array must be malloced, assume caller calls free().
*/
int** generateMatrix(int n)
{
int su=n*n;
int** res=(int**)malloc(sizeof(int*)*n);
for(int i=0;i<n;i++)
{
res[i]=(int*)malloc(sizeof(int)*n);
}
int count=(n+1)/2;
int k=0;
int cc=1;
while(k<count && cc<=su)
{
for(int i=k;i<n-k;i++)
{
res[k][i]=cc;
cc++;
}
for(int i=k+1;i<n-1-k;i++)
{
res[i][n-1-k]=cc;
cc++;
}
if(k!=n-1-k)
{
for(int i=k;i<n-k;i++)
{
res[n-1-k][n-1-i]=cc;
cc++;
}
for(int i=k+1;i<n-1-k;i++)
{
res[n-1-i][k]=cc;
cc++;
}
}
k++;
}
return res;
}
C++
class Solution {
public:
vector<vector<int>> generateMatrix(int n)
{
int su=n*n;
vector<vector<int>> res(n);
for(int i=0;i<n;i++)
{
res[i]=vector<int>(n,0);
}
int count=(n+1)/2;
int k=0;
int cc=1;
while(k<count && cc<=su)
{
for(int i=k;i<n-k;i++)
{
res[k][i]=cc;
cc++;
}
for(int i=k+1;i<n-1-k;i++)
{
res[i][n-1-k]=cc;
cc++;
}
if(k!=n-1-k)
{
for(int i=k;i<n-k;i++)
{
res[n-1-k][n-1-i]=cc;
cc++;
}
for(int i=k+1;i<n-1-k;i++)
{
res[n-1-i][k]=cc;
cc++;
}
}
k++;
}
return res;
}
};
C++ 法2
class Solution {
public:
vector<vector<int>> generateMatrix(int n)
{
vector<vector<int>> res(n,vector<int>(n,0));
int val=1;
int r=0;
int c=0;
while(n>=2)
{
for(int j=c;j<c+n;j++)
{
res[r][j]=val;
val++;
}
for(int i=r+1;i<r+n-1;i++)
{
res[i][c+n-1]=val;
val++;
}
for(int j=c+n-1;j>=c;j--)
{
res[r+n-1][j]=val;
val++;
}
for(int i=r+n-2;i>r;i--)
{
res[i][c]=val;
val++;
}
n-=2;
r++;
c++;
}
if(n)
{
res[r][c]=val;
}
return res;
}
};
python
class Solution:
def generateMatrix(self, n):
"""
:type n: int
:rtype: List[List[int]]
"""
su=n**2
res=[[0 for i in range(n)] for j in range(n)]
count=(n+1)//2
cc=1
k=0
while k<count and cc<=su:
for i in range(k,n-k):
res[k][i]=cc
cc+=1
for i in range(k+1,n-1-k):
res[i][n-1-k]=cc
cc+=1
if k!=n-1-k:
for i in range(k,n-k):
res[n-1-k][n-1-i]=cc
cc+=1
for i in range(k+1,n-1-k):
res[n-1-i][k]=cc
cc+=1
k+=1
return res