【洛谷】 P1518 [USACO2.4]两只塔姆沃斯牛 The Tamworth Two
这个题解法很像一个简单版的输出蛇形矩阵。蛇形矩阵是用flag=1,2,3,4表示四个方向,然后分每个方向的情况,如果到数组边界就将flag变化。
这个题就是把 牛跟人分别碰到障碍物顺时针转 这个行动同样用数字表示出来,直到坐标重合。
最终的结束判断我的方法有点(很)离谱,就是直到积累一定时间还没找到就输出0(在超时的边缘试探)但还是ac了( ̄▽ ̄)
题解:
#include<iostream>
#include<string.h>
#include<algorithm>
using namespace std;
int main()
{
int fx,fy,cx,cy;
char a[10][10];
for(int i=0;i<10;i++)
{
for(int j=0;j<10;j++)
{
cin>>a[i][j];
if(a[i][j]=='F')
{
fx=i;fy=j;
}
if(a[i][j]=='C')
{
cx=i;cy=j;
}
}
}
int vecf=1,vecc=1; //初始方向向上
int time=0,flag=0;
while(!(cx==fx&&cy==fy))
{
//farmer
if(vecf==1)
{
if(fx-1<0||a[fx-1][fy]=='*')
vecf=2;
else
fx=fx-1;
}
else if(vecf==2)
{
if(fy+1>=10||a[fx][fy+1]=='*')
vecf=3;
else
fy=fy+1;
}
else if(vecf==3)
{
if(fx+1>=10||a[fx+1][fy]=='*')
vecf=4;
else
fx=fx+1;
}
else
{
if(fy-1<0||a[fx][fy-1]=='*')
vecf=1;
else
fy=fy-1;
}
//牛
if(vecc==1)
{
if(cx-1<0||a[cx-1][cy]=='*')
vecc=2;
else
cx=cx-1;
}
else if(vecc==2)
{
if(cy+1>=10||a[cx][cy+1]=='*')
vecc=3;
else
cy=cy+1;
}
else if(vecc==3)
{
if(cx+1>=10||a[cx+1][cy]=='*')
vecc=4;
else
cx=cx+1;
}
else
{
if(cy-1<0||a[cx][cy-1]=='*')
vecc=1;
else
cy=cy-1;
}
time++; //或转圈或动弹
if(time>99999999)
{
cout<<0<<endl;
flag=1;
break;
}
}
if(flag!=1)
{
cout<<time<<endl;
}
return 0;
}