solution.md 2.2 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 88
# 螺旋矩阵

<p>给你一个 <code>m</code> 行 <code>n</code> 列的矩阵 <code>matrix</code> ,请按照 <strong>顺时针螺旋顺序</strong> ,返回矩阵中的所有元素。</p><p> </p><p><strong>示例 1:</strong></p><img alt="" src="https://cdn.jsdelivr.net/gh/doocs/leetcode@main/solution/0000-0099/0054.Spiral%20Matrix/images/spiral1.jpg" style="width: 242px; height: 242px;" /><pre><strong>输入:</strong>matrix = [[1,2,3],[4,5,6],[7,8,9]]<strong><br />输出:</strong>[1,2,3,6,9,8,7,4,5]</pre><p><strong>示例 2:</strong></p><img alt="" src="https://cdn.jsdelivr.net/gh/doocs/leetcode@main/solution/0000-0099/0054.Spiral%20Matrix/images/spiral.jpg" style="width: 322px; height: 242px;" /><pre><strong>输入:</strong>matrix = [[1,2,3,4],[5,6,7,8],[9,10,11,12]]<strong><br />输出:</strong>[1,2,3,4,8,12,11,10,9,5,6,7]</pre><p> </p><p><strong>提示:</strong></p><ul>	<li><code>m == matrix.length</code></li>	<li><code>n == matrix[i].length</code></li>	<li><code>1 <= m, n <= 10</code></li>	<li><code>-100 <= matrix[i][j] <= 100</code></li></ul>

## template

```cpp
#include <bits/stdc++.h>
using namespace std;
class Solution
{
public:
	vector<int> spiralOrder(vector<vector<int>> &matrix)
	{
		vector<int> res;
		int hor_top = 0;
		int hor_bottom = matrix.size() - 1;
		int ver_left = 0;
		int ver_right = matrix[0].size() - 1;
		int direction = 0;
		while (hor_top <= hor_bottom && ver_left <= ver_right)
		{
			switch (direction)
			{
			case 0:
				for (int i = ver_left; i <= ver_right; i++)
				{
					res.push_back(matrix[hor_top][i]);
				}
				hor_top++;
				break;
			case 1:
				for (int i = hor_top; i <= hor_bottom; i++)
				{
					res.push_back(matrix[i][ver_right]);
				}
				ver_right--;
				break;
			case 2:
				for (int i = ver_right; i >= ver_left; i--)
				{
					res.push_back(matrix[hor_bottom][i]);
				}
				hor_bottom--;
				break;
			case 3:
				for (int i = hor_bottom; i >= hor_top; i--)
				{
					res.push_back(matrix[i][ver_left]);
				}
				ver_left++;
				break;
			default:
				break;
			}
			direction++;
			direction %= 4;
		}
		return res;
	}
};
```

## 答案

```cpp

```

## 选项

### A

```cpp

```

### B

```cpp

```

### C

```cpp

```