Tom & Jerry can move in the rectangle(10*10),here is a example:
*...*.....
......*...
...*...*..
..........
...*.C....
*.....*...
...*......
..M......*
...*.*....
.*.*......
C symbolise the cat
M symbolise the mouse
* symbolise a obstacle
. symbolise freeland(where tom & jerry can move)
Each second Tom & Jerry can move one step. If they are in the same place we call it "encouter".
What you should pay attetion is the case that if they "swith"(Tom & Jerry simultaneously move a step which will swith their position,see if Tom is at the point A & Jerry is at the point B at first,and after they move their steps their position turn out to be
Tom is at the point B & Jerry is at the point A)IS NOT "encouter"
The principle of their moving:most cases they move directly and if there is a obstacle in his way or the next step will be the border they will use 1 second to turn right.
They face north at the beginning
Input
There are many test cases,The frist rows is the case.the next is the each case.Each case have 10 rows!
Output
a integer T:the time they "encounter",if they has never met at all output -1
Sample Input
1
*...*.....
......*...
...*...*..
..........
...*.C....
*.....*...
...*......
..M......*
...*.*....
.*.*......
题目:eoj1162
题目分析:TOM 和JERRY 有一个起始的坐标,一开始都向上走,直到不能继续向上走则右转。故可按时间顺序推算每一秒时猫和老鼠的位置。当时间值达到一很大值时(我选的是250w),如依然没有相遇,则认为不可能相遇。
也可以枚举每一个点,作两次bfs,注意bfs的规则和普通不同,可以用dx[4]={-1,0,1,0},dy[4]={0,1,0,-1};两个数组表示方向,用d%4表示当前前进方向,若能往前bfs则往前,否则++d;若从两个点bfs得到最短时间相等,则可以相遇,否则不能相遇。
AC代码:
#include <iostream>
#include <cstdio>
#include <cstring>
#include <cmath>
using namespace std;
char map[12][12];
bool visited[12][12];
int dx[4]={-1,0,1,0},dy[4]={0,1,0,-1};
struct Pos{
int x,y;
}c,m;
int main()
{
int t,i,j;
cin>>t;
while(t--){
memset(map,'*',sizeof(map));
for(int i=1;i<=10;++i){
scanf("%s",map[i]+1);
for(intj=1;j<=10;++j){
if(map[i][j]=='C'){
c.x=i;c.y=j;
map[i][j]='.';
}
if(map[i][j]=='M'){
m.x=i;m.y=j;
map[i][j]='.';
}
}
}
for(int i=0;i<12;++i){
map[i][0]=map[i][11]='*';
}
int i=0,d1=0,d2=0;
while(i<2500000){
if(c.x==m.x&& c.y==m.y)
break;
intxx=c.x+dx[d1%4],yy=c.y+dy[d1%4];
if(map[xx][yy]=='.'){
c.x=xx;c.y=yy;
}
else++d1;
xx=m.x+dx[d2%4];yy=m.y+dy[d2%4];
if(map[xx][yy]=='.'){
m.x=xx;m.y=yy;
}
else++d2;
++i;
}
if(i==2500000)i=-1;
cout<<i<<endl;
}
return 0;
}