思路
class Solution {
public:
vector<vector<int>> generateMatrix(int n) {
vector<vector<int>> res(n,vector<int>(n));
int rowbegin = 0, rowend = n-1;
int colbegin = 0, colend = n-1;
int k = 1;
while(rowbegin <= rowend && colbegin <= colend){
for(int i = colbegin; i <= colend; i++){
res[rowbegin][i] = k++;
}
rowbegin++;
for(int i = rowbegin; i <= rowend; i++){
res[i][colend] = k++;
}
colend--;
if(rowend >= rowbegin){
for(int i = colend; i >= colbegin; i--){
res[rowend][i] = k++;
}
rowend--;
}
if(colbegin <= colend){
for(int i = rowend; i >= rowbegin; i--){
res[i][colbegin] = k++;
}
colbegin++;
}
}
return res;
}
};