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]
.
这道题的关键是 M和N有可能不一样,如果剩下一行或者剩下一列的时候要单独处理
外层循环的时候需要确定 while (o_m > 1 && o_n > 1)的条件
class Solution {
public:
vector<int> spiralOrder(vector<vector<int> > &matrix) {
vector<int> retVtr;
if (matrix.size() == 0)
return retVtr;
int n = matrix.size(); //row
int m = matrix[0].size(); //col
int o_n = n;
int o_m = m;
int offset = 0;
while (o_m>1 && o_n>1)
{
for (int j=offset; j<m-offset-1; j++)
{
retVtr.push_back(matrix[offset][j]);
}
for (int i=offset; i<n-offset-1; i++)
{
retVtr.push_back(matrix[i][m-offset-1]);
}
for (int j=m-1-offset; j>offset; j--)
{
retVtr.push_back(matrix[n-offset-1][j]);
}
for (int i=n-1-offset; i>offset; i--)
{
retVtr.push_back(matrix[i][offset]);
}
offset++;
o_m = o_m-2;
o_n = o_n-2;
}
if (o_n==1)
{
for (int j=offset; j<m-offset; j++)
retVtr.push_back(matrix[offset][j]);
}
else if (o_m==1)
{
for (int i=offset; i<n-offset; i++)
retVtr.push_back(matrix[i][offset]);
}
return retVtr;
}
};