# 螺旋矩阵 II
给你一个正整数 n
,生成一个包含 1
到 n2
所有元素,且元素按顺时针顺序螺旋排列的 n x n
正方形矩阵 matrix
。
示例 1:

输入:n = 3
输出:[[1,2,3],[8,9,4],[7,6,5]]
示例 2:
输入:n = 1
输出:[[1]]
提示:
以下程序实现了这一功能,请你填补空白处内容:
```cpp
#include
using namespace std;
class Solution
{
public:
vector> generateMatrix(int n)
{
vector> ans(n, vector(n, 0));
int i, j = 0, time = 0, cnt = 1; //time记录第几圈
ans[0][0] = 1;
while (cnt < n * n)
{
___________________;
time++;
}
return ans;
}
};
```
## template
```cpp
#include
using namespace std;
class Solution
{
public:
vector> generateMatrix(int n)
{
vector> ans(n, vector(n, 0));
int i, j = 0, time = 0, cnt = 1; //time记录第几圈
ans[0][0] = 1;
while (cnt < n * n)
{
for (i = time, j++; j < n - time && cnt < n * n; j++)
ans[i][j] = ++cnt;
for (j--, i++; i < n - time && cnt < n * n; i++)
ans[i][j] = ++cnt;
for (i--, j--; j >= time && cnt < n * n; j--)
ans[i][j] = ++cnt;
for (j++, i--; i > time && cnt < n * n; i--)
ans[i][j] = ++cnt;
time++;
}
return ans;
}
};
```
## 答案
```cpp
for (i = time, j++; j < n - time && cnt < n * n; j++)
ans[i][j] = ++cnt;
for (j--, i++; i < n - time && cnt < n * n; i++)
ans[i][j] = ++cnt;
for (i--, j--; j >= time && cnt < n * n; j--)
ans[i][j] = ++cnt;
for (j++, i--; i > time && cnt < n * n; i--)
ans[i][j] = ++cnt;
```
## 选项
### A
```cpp
for (i = time, j++; j < n - time && cnt < n * n; j++)
ans[i][j] = ++cnt;
for (j--, i++; i < n - time && cnt < n * n; i++)
ans[i][j] = ++cnt;
for (i++, j--; j >= time && cnt < n * n; j--)
ans[i][j] = ++cnt;
for (j--, i++; i > time && cnt < n * n; i--)
ans[i][j] = ++cnt;
```
### B
```cpp
for (i = time, j--; j < n - time && cnt < n * n; j++)
ans[i][j] = ++cnt;
for (j--, i++; i < n - time && cnt < n * n; i++)
ans[i][j] = ++cnt;
for (i--, j++; j >= time && cnt < n * n; j--)
ans[i][j] = ++cnt;
for (j++, i--; i > time && cnt < n * n; i--)
ans[i][j] = ++cnt;
```
### C
```cpp
for (i = time, j++; j < n - time && cnt < n * n; j++)
ans[i][j] = ++cnt;
for (j--, i++; i < n - time && cnt < n * n; i++)
ans[i][j] = ++cnt;
for (i--, j++; j >= time && cnt < n * n; j--)
ans[i][j] = ++cnt;
for (j--, i--; i > time && cnt < n * n; i--)
ans[i][j] = ++cnt;
```