class Solution {
public:
vector<vector<int>> generateMatrix(int n) {
vector<int> a;
vector<vector<int> > answer;
for(int i=0;i<n;i++){
a.push_back(0);
}
for(int i=0;i<n;i++){
answer.push_back(a);
}
int num = n/2+n%2;
int t = 0;
int now = 1;
while(t!=n){
int l = answer.size()-2*t-2;
int r = answer[0].size()-2*t;
for(int i=0;i<r;i++){
answer[t][i+t] = now++;
}
for(int i=0;i<l;i++){
answer[t+i+1][t+r-1] = now++;
}
if(l>=0){
for(int i=0;i<r;i++){
answer[t+l+1][t+r-1-i]=now++;
}
}
if(r>1){
for(int i=0;i<l;i++){
answer[t+l-i][t]=now++;
}
}
t++;
}
return answer;
}
};
先用0填满矩阵,然后利用螺旋矩阵的处理方式,将n平方个数依次填入矩阵中。