思想:
跟上题思路一样。
注意用vector创建二维数组时候指定维数的方法:
vector<vector<int>> res(n,vector<int>(n));
class Solution {
public:
vector<vector<int> > generateMatrix(int n) {
vector<vector<int>> res(n,vector<int>(n));
int beginX = 0, endX = n-1;
int beginY = 0, endY = n-1;
int v = 1;
while(true) {
//from left to right
for(int i=beginY; i<=endY; i++) {
res[beginX][i] = v;
v++;
}
if(++beginX > endX) break;
//from top to bottom
for(int i=beginX; i<=endX; i++) {
res[i][endY] = v;
v++;
}
if(--endY < beginY) break;
//from right to left
for(int i=endY; i>=beginY; i--) {
res[endX][i] = v;
v++;
}
if(--endX < beginX) break;
//from bottom to top
for(int i=endX; i>=beginX; i--) {
res[i][beginY] = v;
v++;
}
if(++beginY > endY) break;
}
return res;
}
};