刷题-力扣-54. 螺旋矩阵
54. 螺旋矩阵
题目链接
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/spiral-matrix/
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
题目描述
给你一个 m 行 n 列的矩阵 matrix ,请按照 顺时针螺旋顺序 ,返回矩阵中的所有元素。
示例 1:
输入:matrix = [[1,2,3],[4,5,6],[7,8,9]]
输出:[1,2,3,6,9,8,7,4,5]
示例 2:
输入:matrix = [[1,2,3,4],[5,6,7,8],[9,10,11,12]]
输出:[1,2,3,4,8,12,11,10,9,5,6,7]
提示:
- m == matrix.length
- n == matrix[i].length
- 1 <= m, n <= 10
- -100 <= matrix[i][j] <= 100
题目分析
- 根据题目描述顺时针输出数组元素
- 使用模拟的方法,模拟顺时针路线
代码
class Solution {
public:
vector<int> spiralOrder(vector<vector<int>>& matrix) {
int circle = 0;
vector<int> res;
int min = matrix.size() > matrix[0].size() ? matrix[0].size() : matrix.size();
while (circle <= min / 2 && circle < min - circle) {
for (int i = circle; i < matrix[circle].size() - circle; i++)
res.push_back(matrix[circle][i]);
for (int i = circle + 1; i < matrix.size() - circle - 1; i++)
res.push_back(matrix[i][matrix[circle].size() - circle - 1]);
for (int i = matrix[circle].size() - circle - 1; i >= circle; i--)
if (matrix.size() - circle - 1 > circle)
res.push_back(matrix[matrix.size() - circle - 1][i]);
for (int i = matrix.size() - circle - 2; i > circle; i--)
if (circle < matrix[circle].size() - circle - 1)
res.push_back(matrix[i][circle]);
circle++;
}
return res;
}
};