题目链接:https://leetcode.cn/problems/spiral-matrix-ii/
C++ 代码如下:
class Solution {
public:
vector<vector<int>> generateMatrix(int n) {
vector<vector<int>> res(n, vector<int>(n));
int x = 0, y = -1;
int cnt = 0, tot = n * n;
while (cnt < tot) {
// 向右
while (y + 1 < n && res[x][y + 1] == 0) {
res[x][++y] = ++cnt;
}
// 向下
while (x + 1 < n && res[x + 1][y] == 0) {
res[++x][y] = ++cnt;
}
// 向左
while (y - 1 >= 0 && res[x][y - 1] == 0) {
res[x][--y] = ++cnt;
}
// 向上
while (x - 1 >= 0 && res[x - 1][y] == 0) {
res[--x][y] = ++cnt;
}
}
return res;
}
};