力扣-数组-59 螺旋矩阵Ⅱ
思路1
记录当前前进方向,然后在到达上下左右的边界时,分别进行处理
代码1
class Solution {
public:
vector<vector<int>> generateMatrix(int n) {
vector< vector<int> > res;
for(int i = 0; i < n; i++){
vector <int> r;
for(int j = 0; j < n; j++){
r.push_back(0);
}
res.push_back(r);
}
int num = 1;
int flag = 0;// 0 right 1 down 2 left 3 up
int right = n - 1, down = n - 1, left = 0, up = 1;
int i=0, j = 0;
while(num <= n*n){
res[i][j] = num;
if(flag == 0){
if(j < right){
j++;
}else{
flag = (flag + 1) % 4;
right -= 1;
i++;
}
}else if(flag == 1){
if(i < down){
i++;
}else{
flag = (flag + 1) % 4;
down -= 1;
j--;
}
}else if(flag == 2){
if(j > left){
j--;
}else{
flag = (flag + 1) % 4;
left += 1;
i--;
}
}else if(flag == 3){
if(i > up){
i--;
}else{
flag = (flag + 1) % 4;
up += 1;
j++;
}
}
num += 1;
}
return res;
}
};
思路2
根据n分解为n/2圈,然后在一圈中用四个for循环更新边,最后更改下一圈的起始位置
class Solution {
public:
vector<vector<int>> generateMatrix(int n) {
vector< vector<int> > res;
for(int i = 0; i < n; i++){
vector <int> r;
for(int j = 0; j < n; j++){
r.push_back(0);
}
res.push_back(r);
}
int num = 1, count = n/2, startX = 0, startY = 0;
int i = 0, j = 0;
int offset = 1;
while(count){
for(j = startY; j < n - offset; j++){
res[startX][j] = num;
num++;
}
for(i = startX; i < n - offset; i++){
res[i][j] = num;
num++;
}
for(; j > startY; j--){
res[i][j] = num;
num++;
}
for(; i > startX; i--){
res[i][j] = num;
num++;
}
offset++;
count--;
startX += 1;
startY += 1;
}
if(n % 2 == 1){
res[startX][startY] = num;
}
return res;
}
};