题目描述:
给定一个包含 m x n 个元素的矩阵(m 行, n 列),请按照顺时针螺旋顺序,返回矩阵中的所有元素。
示例 1:
输入: [ [ 1, 2, 3 ], [ 4, 5, 6 ], [ 7, 8, 9 ] ] 输出: [1,2,3,6,9,8,7,4,5]
示例 2:
输入: [ [1, 2, 3, 4], [5, 6, 7, 8], [9,10,11,12] ] 输出: [1,2,3,4,8,12,11,10,9,5,6,7]
AC C++ Solution:
class Solution {
public:
vector<int> spiralOrder(vector<vector<int>>& matrix) {
vector<int> res;
if(matrix.size() == 0) {
return res;
}
int rowBegin = 0;
int rowEnd = matrix.size()-1;
int colBegin = 0;
int colEnd = matrix[0].size()-1;
while(rowBegin <= rowEnd && colBegin <= colEnd) {
//向右遍历
for (int i = colBegin; i <= colEnd; i++)
res.push_back(matrix[rowBegin][i]);
rowBegin++;
//向下遍历
for (int i = rowBegin; i <= rowEnd; i++)
res.push_back(matrix[i][colEnd]);
colEnd--;
//向左遍历
if(rowBegin <= rowEnd) {
for(int i = colEnd; i >= colBegin; i--)
res.push_back(matrix[rowEnd][i]);
}
rowEnd--;
//向上遍历
if(colBegin <= colEnd) {
for(int i = rowEnd; i >= rowBegin; i--)
res.push_back(matrix[i][colBegin]);
}
colBegin++;
}
return res;
}
};