# 螺旋矩阵 II

<p>给你一个正整数 <code>n</code> ，生成一个包含 <code>1</code> 到 <code>n<sup>2</sup></code> 所有元素，且元素按顺时针顺序螺旋排列的 <code>n x n</code> 正方形矩阵 <code>matrix</code> 。</p><p> </p><p><strong>示例 1：</strong></p><img alt="" src="https://img-service.csdnimg.cn/img_convert/b2086bc4a6e47ebbf922fed2e817b298.jpeg" style="width: 242px; height: 242px;" /><pre><strong>输入：</strong>n = 3<strong><br />输出：</strong>[[1,2,3],[8,9,4],[7,6,5]]</pre><p><strong>示例 2：</strong></p><pre><strong>输入：</strong>n = 1<strong><br />输出：</strong>[[1]]</pre><p> </p><p><strong>提示：</strong></p><ul>	<li><code>1 <= n <= 20</code></li></ul>

以下程序实现了这一功能，请你填补空白处内容：

```cpp
#include <bits/stdc++.h>
using namespace std;
class Solution
{
public:
	vector<vector<int>> generateMatrix(int n)
	{
		vector<vector<int>> ans(n, vector<int>(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 <bits/stdc++.h>
using namespace std;
class Solution
{
public:
	vector<vector<int>> generateMatrix(int n)
	{
		vector<vector<int>> ans(n, vector<int>(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;
```