- 螺旋矩阵
给你一个 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]
class Solution {
public:
vector<int> spiralOrder(vector<vector<int>>& matrix) {
int rows = matrix.size();
vector<int> result;
if(rows == 0) return result;
int cols = matrix[0].size();
int top = 0, bottom = rows-1, left= 0, right = cols-1;
while(top <= bottom && left <= right) {
for(int col = left; col <= right; col++) {
result.push_back(matrix[top][col]);
}
++top;
for(int row = top; row <= bottom; row++) {
result.push_back(matrix[row][right]);
}
--right;
if(top <= bottom) {
for(int col = right; col >= left; col--) {
result.push_back(matrix[bottom][col]);
}
--bottom;
}
if(left <= right) {
for(int row = bottom; row >= top; row--) {
result.push_back(matrix[row][left]);
}
left++;
}
}
return result;
}
};