solution.md 1.8 KB
Newer Older
每日一练社区's avatar
每日一练社区 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87
# 螺旋矩阵 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://cdn.jsdelivr.net/gh/doocs/leetcode@main/solution/0000-0099/0059.Spiral%20Matrix%20II/images/spiraln.jpg" 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>

## template

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

```