此题并不需要利用复杂的数据结构,但需要将问题分解
顺时针遍历二维数组,把二维数组看作由若干个顺时针方向的圈组成,分别对每一圈进行打印
注意到第一圈左上角坐标为(0,0),第二圈(1,1).。。。可将(start, start)作为每圈的起始位置
对5x5的矩阵来说,最后一圈只有一个数字,其位置为(2,2), 2*2<5, 依次列举发现规律,可将cols > 2*start && rows > 2*start 作为循环继续的条件
接下来考虑每一圈的情况,分为四部,从左到右, 从上到下,从右到左,从下到上
不过值得注意的是,最后一圈可能退化成只有一行,只有一列等情况,因此打印每一步时需要进行判断
剑指offer中有详细介绍,如下
代码
class Solution {
public:
vector<int> spiralOrder(vector<vector<int> > &matrix) {
vector<int> result;
int rows = matrix.size();
if(rows<=0)
return result;
int cols = matrix[0].size();
if(cols<=0)
return result;
int start = 0;
while(cols>start*2&&rows>start*2)
{
spiralorderHelper(matrix, rows, cols, start, result);
start++;
}
return result;
}
void spiralorderHelper(vector<vector<int> > &matrix, int rows, int cols, int start, vector<int> &result)
{
int endX = rows - start - 1;
int endY = cols - start - 1;
//from left to right
for(int i = start; i <= endY; ++i)
{
result.push_back(matrix[start][i]);
}
//from top to bottom
if(start < endX)
{
for(int j = start+1; j <= endX; ++j)
{
result.push_back(matrix[j][endY]);
}
}
//from right to left
if(start < endX && start < endY)
{
for(int i = endY-1; i >= start; --i)
result.push_back(matrix[endX][i]);
}
//from bottom to top
if(start < endY && start < endX-1)
{
for(int j = endX-1; j > start; --j)
result.push_back(matrix[j][start]);
}
}
};