标签:c style class blog code java
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]
.
struct Direction
{
int x;
int y;
Direction()
{}
Direction(
int x,
int y)
{
this->x=x;
this->y=y;
}
};
class Solution {
public:
vector<
int> spiralOrder(vector<vector<
int> > &matrix)
{
vector<
int> result;
//find max
int m=matrix.size();
if(m==
0)
return result;
int n=matrix[
0].size();
int FLAG=matrix[
0][
0];
for(
int i=
0;i<m;i++)
for(
int j=
0;j<n;j++)
if(matrix[i][j]>FLAG)
FLAG=matrix[i][j];
FLAG++;
struct Direction dir[
4];
dir[
0].x=
0;dir[
0].y=
1;
dir[
1].x=
1;dir[
1].y=
0;
dir[
2].x=
0;dir[
2].y=-
1;
dir[
3].x=-
1;dir[
3].y=
0;
int cnt=
0;
int x=
0;
int y=-
1;
int diri=
0;
while(cnt<m*n)
{
while(x+dir[diri].x>=
0 && x+dir[diri].x<m && y+dir[diri].y>=
0 && y+dir[diri].y<n
&& matrix[x+dir[diri].x][y+dir[diri].y]!=FLAG)
{
x=x+dir[diri].x;
y=y+dir[diri].y;
result.push_back(matrix[x][y]);
matrix[x][y]=FLAG;
cnt++;
}
diri=(diri+
1)%
4;
}
return result;
}
};
Spiral Matrix,布布扣,bubuko.com
Spiral Matrix
标签:c style class blog code java
原文地址:http://www.cnblogs.com/erictanghu/p/3759396.html