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)
{
vector<int> res;
if (matrix.empty()) return res;
int rh = 0;
int rb = matrix.size() - 1;
int cl = 0;
int cr = matrix[0].size() - 1;
while (rh <= rb || cl <= cr)
{
if(rh <= rb)
for (int i = cl; i <= cr; i++)
res.push_back(matrix[rh][i]);
if (cl <= cr)
for (int i = rh + 1; i <= rb; i++)
res.push_back(matrix[i][cr]);
if (rh < rb)
for (int i = cr - 1; i >= cl; i--)
res.push_back(matrix[rb][i]);
if (cl < cr)
for (int i = rb - 1; i >= rh + 1; i--)
res.push_back(matrix[i][cl]);
rh++; rb--; cl++;cr--;
}
return res;
}
};
要点在于四个if判断,只有if里条件满足才有遍历的意义