题目
注意的点
最后只剩一行或者只剩一列的情况,用tot<=n*n来控制。
代码
class Solution {
public:
vector<vector<int>> generateMatrix(int n) {
int tot = 1, lx = 0, ly = 0, rx= n - 1, ry = n - 1;
vector<vector<int>> ans(n, vector<int>(n,0));
while(tot <= n * n){
for(int col = ly; col <= ry; col ++) ans[lx][col] = tot++;
for(int row = lx + 1; row <= rx; row++) ans[row][ry] = tot++;
for(int col = ry - 1; col >= ly && tot <= n * n; col--) ans[rx][col] = tot++;
for(int row = rx - 1; row > lx && tot <= n * n; row -- ) ans[row][ly] = tot++;
lx++, ly++, rx--, ry--;
}
return ans;
}
};