终止条件:两者相遇,并且在该分钟末尾。然后计算时间。
判断方法:如果两个物体先后两次从同一个方向走到同一个地点,我们就可以说它们陷入了死循环。这边可以通过生成专属值的方法来判断:农夫的x坐标+他的y坐标* 10+奶牛的x坐标* 100+奶牛的y坐标* 1000+农夫的方向* 10000+奶牛的方向* 40000(农夫方向最多为4)
#include<bits/stdc++.h>
using namespace std;
char m[12][12]; //地图
int f[3],c[3],ans,zsz; //农夫,奶牛,秒数,专属值
// f[0]代表方向 f[1]代表x坐标 f[2]代表y坐标
bool zt[160005]; //记录专属值是否出现
void move(int x,int y,int dir,int type) //x,y为x,y坐标,dir为方向,type为类型:农夫为0,奶牛为1
{
if(dir==0){
if(m[x][y+1]=='*') if(type==0) f[0]=1; else c[0]=1;
else if(type==0) f[2]++; else c[2]++;
}else if(dir==1){
if(m[x+1][y]=='*') if(type==0) f[0]=2; else c[0]=2;
else if(type==0) f[1]++; else c[1]++;
}else if(dir==2){
if(m[x][y-1]=='*') if(type==0) f[0]=3; else c[0]=3;
else if(type==0) f[2]--; else c[2]--;
} else{
if(m[x-1][y]=='*') if(type==0) f[0]=0; else c[0]=0;
else if(type==0) f[1]--; else c[1]--;
}
}
bool pd(){ //判断循环终止条件:如果奶牛坐标与农夫坐标相等,则他们重叠,返回0,退出循环
if (f[1]==c[1]&&f[2]==c[2]) return 0;
else return 1;
}
int main()
{
for(int i=0;i<=11;i++) m[i][0]='*',m[i][11]='*';
for(int i=1;i<=10;i++) m[0][i]='*',m[11][i]='*';
for(int i=10;i>=1;i--){ //这边WA了一下 要注意从上到下读入二维数组
for(int j=1;j<=10;j++){
cin>>m[j][i];
if(m[j][i]=='F') f[1]=j,f[2]=i;
if(m[j][i]=='C') c[1]=j,c[2]=i;
}
}
while (pd()){ //模拟每秒
zsz=f[1]+f[2]*10+c[1]*100+c[2]*1000+f[0]*10000+c[0]*40000;
if(zt[zsz]){ //死循环了就输出0并结束程序
cout<<0<<endl;
return 0;
}
zt[zsz]=1;
move(f[1],f[2],f[0],0); //依次移动农夫和奶牛
move(c[1],c[2],c[0],1);
ans++;
}
cout<<ans<<endl;
return 0;
}