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.size() == 0)
return vector<int> ();
vector<int> res;
int beginx = 0;
int beginy = 0;
int endx = matrix[0].size()-1;
int endy = matrix.size()-1;
while(true)
{
for(int i = beginx; i <= endx; i++)
{
res.push_back(matrix[beginy][i]);
}
if(++beginy > endy) break;
for(int i = beginy; i <= endy; i++)
{
res.push_back(matrix[i][endx]);
}
if(beginx > --endx) break;
for(int i = endx; i >= beginx; i--)
{
res.push_back(matrix[endy][i]);
}
if(beginy > --endy) break;
for(int i = endy; i >= beginy; i--)
{
res.push_back(matrix[i][beginx]);
}
if(++beginx > endx) break;
}
return res;
}
};