- 螺旋矩阵 II
给你一个正整数 n ,生成一个包含 1 到 n2 所有元素,且元素按顺时针顺序螺旋排列的 n x n 正方形矩阵 matrix 。
示例 1:
输入:n = 3
输出:[[1,2,3],[8,9,4],[7,6,5]]
【思路】:从外向内,顺时针遍历,每条边始终保持“左闭右开”。边长为奇数时,单独处理最里面的位置。
class Solution {
public:
vector<vector<int>> generateMatrix(int n) {
vector<vector<int>> ret(n, vector(n, 0));
int layers = n / 2;
int i = 0, j = 0;
int startx = 0, starty = 0;
int offset = 1;
int count = 1;
while(layers--){
for(j = starty; j<starty + n - offset; j++){
ret[startx][j] = count++;
}
for(i = startx; i < startx + n - offset; i++) {
ret[i][j] = count++;
}
for(; j > starty; j--) {
ret[i][j] = count++;
}
for(; i > startx; i--) {
ret[i][j] = count++;
}
startx++;
starty++;
offset += 2;
}
if((n % 2) == 1){ // 为奇数时,处理最里面的位置
ret[startx][starty] = count++;
}
return ret;
}
};
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/spiral-matrix-ii/