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]
.
struct node{
int x,y;
node(int i,int j):x(i),y(j){}
};
int fang[4][2]={0,1,1,0,0,-1,-1,0};
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();
vector<vector<bool>> flag(m);
for(int i=0;i<m;i++)flag[i].assign(n,false);
queue<node> que;
que.push(node(0,0));
result.push_back(matrix[0][0]);
flag[0][0]=true;
int direct=0;
while(!que.empty()){
node cur=que.front();que.pop();
int nx=cur.x+fang[direct%4][0];
int ny=cur.y+fang[direct%4][1];
if(nx>=0&&nx<m&&ny>=0&&ny<n&&!flag[nx][ny]){
flag[nx][ny]=true;
que.push(node(nx,ny));
result.push_back(matrix[nx][ny]);
}
else {
direct++;
nx=cur.x+fang[direct%4][0];
ny=cur.y+fang[direct%4][1];
if(nx>=0&&nx<m&&ny>=0&&ny<n&&!flag[nx][ny]){
flag[nx][ny]=true;
que.push(node(nx,ny));
result.push_back(matrix[nx][ny]);
}
}
}
return result;
}
};