# 螺旋矩阵 II
给你一个正整数 n
,生成一个包含 1
到 n2
所有元素,且元素按顺时针顺序螺旋排列的 n x n
正方形矩阵 matrix
。
示例 1:
输入:n = 3
输出:[[1,2,3],[8,9,4],[7,6,5]]
示例 2:
输入:n = 1
输出:[[1]]
提示:
以下错误的选项是?
## aop
### before
```cpp
#include
using namespace std;
```
### after
```cpp
int main()
{
Solution sol;
int n = 3;
vector> res;
res = sol.generateMatrix(n);
for (auto i : res)
{
for (auto j : i)
cout << j << " ";
cout << endl;
}
return 0;
}
```
## 答案
```cpp
class Solution
{
public:
vector> generateMatrix(int n)
{
vector> ans(n, vector(n, 0));
int c = n / 2;
int val = 1;
for (int i = 0; i < c; ++i, n -= 2)
{
for (int col = i; col < i + n; ++col)
ans[i][col] = val++;
if (n == 1)
return ans;
for (int row = i + 1; row < i + n; ++row)
ans[row][i + n - 1] = val++;
for (int col = i + n - 2; col >= i; --col)
ans[i + n - 1][col] = val++;
for (int row = i + n - 2; row > i; --row)
ans[row][i] = val++;
}
return ans;
}
};
```
## 选项
### A
```cpp
class Solution
{
public:
vector> generateMatrix(int n)
{
vector> matrix(n, vector(n));
int u = 0, d = n - 1, l = 0, r = n - 1, k = 0;
while (true)
{
for (int col = l; col <= r; col++)
matrix[u][col] = ++k;
if (++u > d)
break;
for (int row = u; row <= d; row++)
matrix[row][r] = ++k;
if (--r < l)
break;
for (int col = r; col >= l; col--)
matrix[d][col] = ++k;
if (--d < u)
break;
for (int row = d; row >= u; row--)
matrix[row][l] = ++k;
if (++l > r)
break;
}
return matrix;
}
};
```
### B
```cpp
class Solution
{
public:
vector> generateMatrix(int n)
{
vector> result(n, vector(n, 0));
int top = 0, right = n - 1, left = 0, bottom = n - 1;
int k = 1;
while (k <= n * n)
{
for (int i = left; i <= right; i++)
result[top][i] = k++;
top++;
for (int i = top; i <= bottom; i++)
result[i][right] = k++;
right--;
for (int i = right; i >= left; i--)
result[bottom][i] = k++;
bottom--;
for (int i = bottom; i >= top; i--)
result[i][left] = k++;
left++;
}
return result;
}
};
```
### C
```cpp
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;
}
};
```