题目链接:54. 螺旋矩阵
题目:
给你一个 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
思路和算法:
这题和剑指 Offer 29. 顺时针打印矩阵相同,解法一致,思路在这里就不写了,请见力扣:剑指 Offer 29. 顺时针打印矩阵。
代码(c++):
//按层模拟
class Solution {
public:
vector<int> spiralOrder(vector<vector<int>>& matrix) {
if (!matrix.size() && !matrix[0].size()) return {};
vector<int> res;
int rows = matrix.size(); //最外层行数
int columns = matrix[0].size(); //最外层列数
//左上角:[top, left] 右下角:[bottom, right]
int top = 0, left = 0, bottom = rows - 1, right = columns - 1;
while (left <= right && top <= bottom) {
//遍历top行:top --> right
for (int column = left; column <= right; ++column) {
res.push_back(matrix[top][column]);
}
//遍历right列:top+1 --> bottom
for (int row = top + 1; row <= bottom; ++row) {
res.push_back(matrix[row][right]);
}
//判断是否到了最里层
if (left < right && top < bottom) {
//遍历bottom行:right-1 --> left+1
for (int column = right - 1; column > left; --column) {
res.push_back(matrix[bottom][column]);
}
//遍历left列:bottom --> top+1
for (int row = bottom; row > top; --row) {
res.push_back(matrix[row][left]);
}
}
top++;
left++;
bottom--;
right--;
}
return res;
}
};