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) {
int m=matrix.size();
if(m==0) return vector<int>();
int n=matrix[0].size();
if(n==0) return vector<int>();
vector<int>res(m*n);
int rstart=0,cstart=0;
int rend=m-1,cend=n-1;
int index=0;
while(rstart<=rend&&cstart<=cend){
int r=rstart,c=cstart;
if(cstart==cend){
while(rstart<=rend) res[index++]=matrix[rstart++][cstart];
break;
}
if(rstart==rend){
while(cstart<=cend) res[index++]=matrix[rstart][cstart++];
break;
}
while(c<=cend){
res[index++]=matrix[r][c];
c++;
}
c--;r++;
while(r<=rend){
res[index++]=matrix[r][c];
r++;
}
r--;c--;
while(c>=cstart){
res[index++]=matrix[r][c];
c--;
}
c++;r--;
while(r>rstart){
res[index++]=matrix[r][c];
r--;
}
rstart++;
cstart++;
rend--;
cend--;
}
return res;
}
};