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> result;
if (matrix.empty())
return result;
int bR = 0, bC = 0;
int eR = matrix.size() - 1, eC = matrix[0].size() - 1;
while (true) {
for (int j = bC; j <= eC; ++j)
result.push_back(matrix[bR][j]);
if (++bR > eR) break;
for (int i = bR; i<= eR; ++i)
result.push_back(matrix[i][eC]);
if (bC > --eC) break;
for (int j = eC; j>= bC; --j)
result.push_back(matrix[eR][j]);
if (bR > --eR) break;
for (int i = eR; i >= bR; --i)
result.push_back(matrix[i][bC]);
if (++bC > eC) break;
}
return result;
}
};