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].
Subscribe to see which companies asked this question
class Solution {
public:
vector<int> spiralOrder(vector<vector<int>>& matrix) {
int len = matrix.size();
vector<int> ret;
if(len == 0) return ret;
int rows = len, cols = matrix[0].size();
int beginRow=0, endRow=rows-1, beginCol=0, endCol=cols-1;
for(; beginRow <= endRow && beginCol <= endCol; beginRow++, endRow--, beginCol++, endCol--) {
int tmpCol = beginCol;
while(tmpCol <= endCol) {
ret.push_back(matrix[beginRow][tmpCol]);
tmpCol++;
}
int tmpRow = beginRow+1;
while(tmpRow <= endRow) {
ret.push_back(matrix[tmpRow][endCol]);
tmpRow++;
}
tmpCol = endCol-1;
while(tmpCol >= beginCol && endRow > beginRow) {
ret.push_back(matrix[endRow][tmpCol]);
tmpCol--;
}
tmpRow=endRow-1;
while(tmpRow > beginRow && endCol > beginCol) {
ret.push_back(matrix[tmpRow][beginCol]);
tmpRow--;
}
}
return ret;
}
};