Wednesday, February 17, 2016

LeetCode Q54: Spiral Matrix

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 m=matrix.size();
int n=matrix[0].size();
int u=n, r=m, d=n, l=m;
int row=0, col=0;
while(true){
if(u==0)
return result;
int t=col+u;
for(;col<t; col++){
result.push_back(matrix[row][col]);
}
col--; r--; l--; row++;
if(r==0)
return result;
t=row+r;
for(;row<t; row++){
result.push_back(matrix[row][col]);
}
row--; d--; u--; col--;
if(d==0)
return result;
t=col-(d-1);
for(;col>=t; col--){
result.push_back(matrix[row][col]);
}
col++; l--; r--; row--;
if(l==0)
return result;
t=row-(l-1);
for(;row>=t; row--){
result.push_back(matrix[row][col]);
}
row++; u--; d--; col++;
}
}
};

No comments:

Post a Comment