思路:模拟,给出上下左右4个方向的边界,逐步收缩
class Solution {
public:
vector<vector<int>> generateMatrix(int n) {
int left = 0;
int right = n-1;
int top = 0;
int bottom = n-1;
int k = 1;
vector<vector<int>> ans (n,vector<int>(n));
while(k <= n*n){
for(int i = left;i<=right;++i,++k) ans[top][i] = k;
top++;
for(int i = top;i<=bottom;++i,++k) ans[i][right] = k;
right--;
for(int i = right;i>=left;--i,++k) ans[bottom][i] = k;
bottom--;
for(int i = bottom;i>=top;--i,++k) ans[i][left] = k;
left++;
}
return ans;
}
};