难度:1
1Y又失败。。
解法:模拟。。
class Solution
{
public:
const int LEFT=0;
const int RIGHT=1;
const int DOWN=2;
const int UP=3;
vector<int> spiralOrder(vector<vector<int> > &matrix)
{
vector<int>ans;
if(matrix.size() == 0) return ans;
if(matrix.size() == 1) return matrix[0];
if(matrix[0].size() == 0) return ans;
int m=matrix.size();//row
int n=matrix[0].size();//col
int cur_x=0,cur_y=0,cur_dir=RIGHT;
ans.push_back(matrix[cur_x][cur_y]);
int border_left=0;
int border_right=n-1;
int border_down=m-1;
int border_up=0;
while(border_left<=border_right&&border_up<=border_down)
{
if(cur_x == border_up && cur_x == border_down && cur_y == border_left && cur_y == border_right)
{
break;
}
int next_x,next_y;
if(cur_dir == LEFT)
{
next_x=cur_x;
next_y=cur_y-1;
if(next_y < border_left)
{
cur_dir=UP;
border_down--;
continue;
}
}
else if(cur_dir == RIGHT)
{
next_x=cur_x;
next_y=cur_y+1;
if(next_y>border_right)
{
cur_dir=DOWN;
border_up++;
continue;
}
}
else if(cur_dir == DOWN)
{
next_x=cur_x+1;
next_y=cur_y;
if(next_x>border_down)
{
cur_dir=LEFT;
border_right--;
continue;
}
}
else
{
next_x=cur_x-1;
next_y=cur_y;
if(next_x<border_up)
{
cur_dir=RIGHT;
border_left++;
continue;
}
}
ans.push_back(matrix[next_x][next_y]);
cur_x=next_x;
cur_y=next_y;
}
return ans;
}
};