Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in spiral order.
class Solution {
public:
vector<int> spiralOrder(vector<vector<int>>& matrix)
{
vector<int> ret;
if (matrix.empty()) return ret;
int row = matrix.size();
int col = matrix[0].size();
int rowBegin = 0;
int rowEnd = row - 1;
int colBegin = 0;
int colEnd = col - 1;
while (rowBegin <= rowEnd && colBegin <= colEnd)
{
for (int j = colBegin; j <= colEnd; j++)
{
ret.push_back(matrix[rowBegin][j]);
}
rowBegin++;
for (int i = rowBegin; i <= rowEnd; i++)
{
ret.push_back(matrix[i][colEnd]);
}
colEnd--;
if (rowBegin <= rowEnd)
{
for (int j = colEnd; j >= colBegin; j--)
{
ret.push_back(matrix[rowEnd][j]);
}
}
rowEnd--;
if (colBegin <= colEnd)
{
for (int i = rowEnd; i >= rowBegin; i--)
{
ret.push_back(matrix[i][colBegin]);
}
}
colBegin++;
}
return ret;
}
};