# 螺旋矩阵 II
给你一个正整数 n
,生成一个包含 1
到 n2
所有元素,且元素按顺时针顺序螺旋排列的 n x n
正方形矩阵 matrix
。
示例 1:
输入:n = 3
输出:[[1,2,3],[8,9,4],[7,6,5]]
示例 2:
输入:n = 1
输出:[[1]]
提示:
## template
```cpp
#include
using namespace std;
class Solution
{
public:
vector> generateMatrix(int n)
{
vector> matrix(n, vector(n));
int direction = 0;
int hor_top = 0;
int hor_bottom = n - 1;
int ver_left = 0;
int ver_right = n - 1;
int num = 0;
while (num < n * n)
{
switch (direction)
{
case 0:
for (int i = ver_left; i <= ver_right; i++)
{
matrix[hor_top][i] = ++num;
}
hor_top++;
break;
case 1:
for (int i = hor_top; i <= hor_bottom; i++)
{
matrix[i][ver_right] = ++num;
}
ver_right--;
break;
case 2:
for (int i = ver_right; i >= ver_left; i--)
{
matrix[hor_bottom][i] = ++num;
}
hor_bottom--;
break;
case 3:
for (int i = hor_bottom; i >= hor_top; i--)
{
matrix[i][ver_left] = ++num;
}
ver_left++;
break;
}
direction++;
direction %= 4;
}
return matrix;
}
};
```
## 答案
```cpp
```
## 选项
### A
```cpp
```
### B
```cpp
```
### C
```cpp
```