2.4.1 The Tamworth Two 两只塔姆沃斯牛

2.4.1 The Tamworth Two 两只塔姆沃斯牛

. 空地
* 障碍物
C 两头牛
F 农民John

```*...*.....
......*...
...*...*..
..........
...*.F....
*.....*...
...*......
..C......*
...*.*....
.*.*......

```

Lines 1-10:

``````*...*.....
......*...
...*...*..
..........
...*.F....
*.....*...
...*......
..C......*
...*.*....
.*.*......``````

``````49
``````

``````#include <stdio.h>

int disc,disf,cx,cy,fx,fy,sum;
int dis[4][2]={{-1,0},{0,1},{1,0},{0,-1}};//↑ → ↓ ←
char map[11][11];

int check(int a,int b){
if(a>=0 && a<10 && b>=0 && b<10)
return 1;
return 0;
}

void solve(int ax,int ay,int bx,int by,int num){
int x,y;
if(sum)
return ;
if(num>160000){//终止条件
if(ax!=bx || ay!=by)
sum=-1;
else
sum=num;
return ;//找不到
}
if(ax==bx && ay==by){//找到
sum=num;
return ;
}
x=dis[disf][0];
y=dis[disf][1];
if(check(ax+x,ay+y) && map[ax+x][ay+y]!='*')
ax+=x,ay+=y;
else
disf=(disf+1)%4;
x=dis[disc][0];
y=dis[disc][1];
if(check(bx+x,by+y) && map[bx+x][by+y]!='*')
bx+=x,by+=y;
else
disc=(disc+1)%4;
solve(ax,ay,bx,by,num+1);
}

int main(){
int i,j;
sum=fx=fy=cx=cy=0;
for(i=0;i<10;i++){
for(j=0;j<10;j++){
scanf("%c",&map[i][j]);
if(map[i][j]=='F')
fx=i,fy=j;
if(map[i][j]=='C')
cx=i,cy=j;
}
getchar();
}
solve(fx,fy,cx,cy,0);
printf("%d\n",sum==-1?0:sum);
return 0;
}``````

``````#include <stdio.h>

int disc,disf,cx,cy,fx,fy,sum;
int dis[4][2]={{-1,0},{0,1},{1,0},{0,-1}};//↑ → ↓ ←
char map[11][11];

int check(int a,int b){
if(a>=0 && a<10 && b>=0 && b<10)
return 1;
return 0;
}

void solve(int ax,int ay,int bx,int by,int num){
int x,y;
if(sum)
return ;
if(num>160000){//终止条件
if(ax!=bx || ay!=by)
sum=-1;
else
sum=num;
return ;//找不到
}
if(ax==bx && ay==by){//找到
sum=num;
return ;
}
x=dis[disf][0];
y=dis[disf][1];
if(check(ax+x,ay+y) && map[ax+x][ay+y]!='*')
ax+=x,ay+=y;
else
disf=(disf+1)%4;
x=dis[disc][0];
y=dis[disc][1];
if(check(bx+x,by+y) && map[bx+x][by+y]!='*')
bx+=x,by+=y;
else
disc=(disc+1)%4;
solve(ax,ay,bx,by,num+1);
}

int main(){
int i,j;
sum=fx=fy=cx=cy=0;
for(i=0;i<10;i++){
for(j=0;j<10;j++){
scanf("%c",&map[i][j]);
if(map[i][j]=='F')
fx=i,fy=j;
if(map[i][j]=='C')
cx=i,cy=j;
}
getchar();
}
solve(fx,fy,cx,cy,0);
printf("%d\n",sum==-1?0:sum);
return 0;
}``````