题目描述
Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in spiral order.
For example,
Given the following matrix:
[ [ 1, 2, 3 ], [ 4, 5, 6 ], [ 7, 8, 9 ] ]
You should return[1,2,3,6,9,8,7,4,5].
分析:螺旋数组问题
class Solution {
public:
vector<int> spiralOrder(vector<vector<int> > &matrix)
{
if(matrix.empty())
return vector<int>();
int m=matrix.size(),n=matrix[0].size();
int up = 0,down = m-1,left = 0,right = n-1;
vector<int> res;
while(1)
{
for(int i=left;i<=right;i++)
res.push_back(matrix[up][i]);
if(++up > down) break;
for(int j=up;j<=down;j++)
res.push_back(matrix[j][right]);
if(--right<left) break;
for(int i=right;i>=left;i--)
res.push_back(matrix[down][i]);
if(--down<up) break;
for(int j=down;j>=up;j--)
res.push_back(matrix[j][left]);
if(++left > right) break;
}
return res;
}
};