给定一个正整数 n,生成一个包含 1 到 n2 所有元素,且元素按顺时针顺序螺旋排列的正方形矩阵。
示例:
输入: 3 输出: [ [ 1, 2, 3 ], [ 8, 9, 4 ], [ 7, 6, 5 ] ]
题目标签:Array
题目链接:LeetCode / LeetCode中国
Language | Runtime | Memory |
---|---|---|
cpp | 4 ms | 925.7 KB |
class Solution {
public:
vector<vector<int>> generateMatrix(int n) {
vector<vector<int>> res = vector<vector<int>>(n, vector<int>(n, 0));
if (n < 1) { return res; }
int x = 0;
int y = 0;
int num = 1;
for (int step=n-1; step>=1; step-=2) {
for (int i=0; i<step; ++i) {
res[x][y++] = num++;
}
for (int i=0; i<step; ++i) {
res[x++][y] = num++;
}
for (int i=0; i<step; ++i) {
res[x][y--] = num++;
}
for (int i=0; i<step; ++i) {
res[x--][y] = num++;
}
x++;
y++;
}
if (n % 2) {
res[n/2][n/2] = n * n;
}
return res;
}
};