给定一个正整数 n,生成一个包含 1 到 n2 所有元素,且元素按顺时针顺序螺旋排列的正方形矩阵。
示例:
输入: 3
输出:
[
[ 1, 2, 3 ],
[ 8, 9, 4 ],
[ 7, 6, 5 ]
]
class Solution {
public:
vector<vector<int>> generateMatrix(int n) {
int res[n][n] ;
int num=1, d=n-1, x=(n-d)/2, y=(n-d)/2;
while (d > 0) {
for(int i=0; i<d; i++) res[x][y+i] = num++;
y += d;
for(int i=0; i<d; i++) res[x+i][y] = num++;
x += d;
for(int i=0; i<d; i++) res[x][y-i] = num++;
y = (n-d) / 2;
for(int i=0; i<d; i++) res[x-i][y] = num++;
d -= 2;
x = (n-d) / 2;
y = (n-d) / 2;
}
if (d==0) res[x][y] = num;
vector<vector<int>> a;
for(int i=0; i<n; i++)
{
vector<int> a1;
for(int j=0; j<n; j++)
{
a1.push_back(res[i][j]);
}
a.push_back(a1);
}
return(a);
}
};