给你一个正整数 n
,生成一个包含 1
到 n2
所有元素,且元素按顺时针顺序螺旋排列的 n x n
正方形矩阵 matrix
。
示例 1:
输入:n = 3 输出:[[1,2,3],[8,9,4],[7,6,5]]
示例 2:
输入:n = 1 输出:[[1]]
提示:
1 <= n <= 20
题目链接:https://leetcode.cn/problems/spiral-matrix-ii/description/
思路:使用四个for,螺旋遍历
class Solution {
public:
vector<vector<int>> generateMatrix(int n) {
vector<vector<int>> nums(n, vector<int>(n,0));
int startx = 0, starty = 0, offset = 1, count = 1, while_times = n / 2;
while(while_times--){
int x = startx, y = starty;
for( ; y < n - offset; y++){
nums[x][y] = count++;
}
for( ; x < n - offset; x++){
nums[x][y] = count++;
}
for( ; y > starty; y--){
nums[x][y] = count++;
}
for( ; x > startx; x--){
nums[x][y] = count++;
}
startx++;
starty++;
offset++;
}
if(n % 2 == 1){
nums[startx][starty] = count;
}
return nums;
}
};