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]
.
迭代递归都可以。
vector<int> spiralOrder(vector<vector<int> > &matrix) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
vector<int> result;
if(matrix.empty()||matrix[0].empty())
return result;
int rows = matrix.size();
int cols = matrix[0].size();
int startx = 0,starty = 0;
while(rows>2*startx&&cols>2*starty)
{
int endx = rows-1-startx;
int endy = cols-1-starty;
//top --一定ok的
for(int i=starty;i<=endy;i++)
result.push_back(matrix[startx][i]);
//right
for(int i=startx+1;i<=endx;i++)
result.push_back(matrix[i][endy]);
//bottom
if(endx>startx)
{
for(int i=endy-1;i>=starty;i--)
result.push_back(matrix[endx][i]);
}
if(endy>starty)
{
//left
for(int i=endx-1;i>startx;i--)
result.push_back(matrix[i][starty]);
}
++startx;
++starty;
}
return result;
}