给你一个正整数n
,生成一个包含1到
n
2
n^2
n2所有元素,且元素按顺时针顺序螺旋排列的n x n
正方形矩阵matrix
。
示例1:
输入:n = 3
输出:[[1,2,3],[8,9,4],[7,6,5]]
示例2:
输入:n = 1
输出:[[1]]
提示
- 1 ⩽ n ⩽ 20 1 \leqslant {n}\leqslant{20} 1⩽n⩽20
class Solution {
public:
vector<vector<int>> generateMatrix(int n) {
vector<vector<int>> res(n, vector<int>(n, 0));
int loop = n / 2;
int count = 1;
int startx = 0, starty = 0;
int i, j;
int offset = 1;
while (loop--) {
for (j = starty; j < starty + n - offset; j++) {
res[startx][j] = count++;
}
for (i = startx; i < startx + n - offset; i++) {
res[i][j] = count++;
}
for (; j > starty; j--) {
res[i][j] = count++;
}
for (; i > startx; i--) {
res[i][j] = count++;
}
startx++;
starty++;
offset += 2;
}
if (n%2 == 1) {
res[n/2][n/2] = count;
}
return res;
}
};
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)