Right Turn
题目描述
frog is trapped in a maze. The maze is infinitely large and divided into grids. It also consists of n obstacles, where the i-th obstacle lies in grid (xi,yi).
frog is initially in grid (0,0), heading grid (1,0). She moves according to The Law of Right Turn: she keeps moving forward, and turns right encountering a obstacle.
The maze is so large that frog has no chance to escape. Help her find out the number of turns she will make.
Input
The input consists of multiple tests. For each test:
The first line contains 1 integer n (0≤n≤103). Each of the following n lines contains 2 integers xi,yi. (|xi|,|yi|≤109,(xi,yi)≠(0,0), all (xi,yi) are distinct)
Output
For each test, write 1 integer which denotes the number of turns, or ``-1’’ if she makes infinite turns.
Sample Input
2
1 0
0 -1
1
0 1
4
1 0
0 1
0 -1
-1 0
Sample Output
2
0
-1
题目大意
一个迷宫有n块石头,一个人从(0,0)出发,一开始是面向右边,如果他遇到石头就要向右转,问这个人走出迷宫要转几次弯,如果会无限次转弯就输出-1
思路
直接模拟,遇到障碍就标记一下此时到这个障碍的方向,然后右转,如果以后又以同样的方向碰到这个障碍,就直接跳出循环。否则肯定可以出去。
代码
#include<iostream>
#include<stdio.h>
#include<string.h>
#include<algorithm>
#include<map>
#include<vector>
#include<queue>
#include<stack>
#include<string>
#include<math.h>
#include<bitset>
#include<stdlib.h>
using namespace std;
typedef long long ll;
const int inf=0x3f3f3f3f;
const double pi=acos(-1.0);
const int N=1e5+10;
struct note
{
int x,y;
} node[1010];
map<int,map<int,map<int,int> > >xiao;
int main()
{
int n;
while(~scanf("%d",&n))
{
xiao.clear();
for(int i=0; i<n; i++)
scanf("%d%d",&node[i].x,&node[i].y);
int mov=1;
int now_x=0,now_y=0;
int flag=0;
int cnt=0;
while(1)
{
int xx=inf;
int yy=-inf;
int xx2=-inf;
int yy2=inf;
if(mov==1)
{
for(int i=0; i<n; i++)
{
if(node[i].y==now_y&&node[i].x>now_x)
{
if(node[i].x<xx)
xx=node[i].x;
}
}
if(xx==inf)
{
flag=1;
break;
}
else
{
cnt++;
mov=2;
now_x=xx-1;
if(xiao[xx][now_y][1]==1)
break;
xiao[xx][now_y][1]=1;
}
}
else if(mov==2)
{
for(int i=0; i<n; i++)
{
if(now_x==node[i].x&&now_y>node[i].y)
{
if(node[i].y>yy)
yy=node[i].y;
}
}
if(yy==-inf)
{
flag=1;
break;
}
else
{
cnt++;
mov=3;
now_y=yy+1;
if(xiao[now_x][yy][2]==1)
break;
xiao[now_x][yy][2]=1;
}
}
else if(mov==3)
{
for(int i=0; i<n; i++)
{
if(node[i].y==now_y&&now_x>node[i].x)
{
if(node[i].x>xx2)
xx2=node[i].x;
}
}
if(xx2==-inf)
{
flag=1;
break;
}
else
{
cnt++;
mov=4;
now_x=xx2+1;
if(xiao[xx2][now_y][3]==1)
break;
xiao[xx2][now_y][3]=1;
}
}
else
{
for(int i=0; i<n; i++)
{
if(node[i].x==now_x&&now_y<node[i].y)
{
if(node[i].y<yy2)
yy2=node[i].y;
}
}
if(yy2==inf)
{
flag=1;
break;
}
else
{
cnt++;
mov=1;
now_y=yy2-1;
if(xiao[now_x][yy2][4]==1)
break;
xiao[now_x][yy2][4]=1;
}
}
}
if(flag)
printf("%d\n",cnt);
else
printf("-1\n");
}
return 0;
}