class Solution {
public:
vector<int> spiralOrder(vector<vector<int>>& matrix) {
vector<int> r;
int row = matrix.size();
if(row == 0 )
return r;
int col = matrix[0].size();
if(col == 0)
return r;
//left->right
int i = -1, j =-1;
int times = 0;
while(1)
{
i++;
j++;
if(!(i>= 0 && i< row && j>= 0 && j < col - times))
break;
while(j < col - times)
{
r.push_back(matrix[i][j]);
j++;
}
//top -> bottom
i++;
j--;
if(!(i>=0&& j>= 0 && j < col && i < row - times ))
break;
while( i < row - times )
{
r.push_back(matrix[i][j]);
i++;
}
//right -> left
i--;
j--;
if(!(i >= 0&& i < row && j < col && j >= times))
break;
while( j >= times)
{
r.push_back(matrix[i][j]);
j--;
}
//bottom -> top
j++;
i--;
if(!(i < row && j >=0 && j < col && i > times))
break;
while(i > times)
{
r.push_back(matrix[i][j]);
i--;
}
times++;
}
return r;
}
};
Spiral Matrix
最新推荐文章于 2024-07-06 15:27:08 发布