这道题大概题意:输入地图, # :表示墙; . :表示路; Y和M :分别表示两个人; @ :表示KFC. 两个人都要去同一家KFC,但是地图上有很多KFC,输出最短的路程和.(注:每步的路程是11)
思路:以两个人为基准点先后BFS,每次找到KFC的位置后分别存入path1和path2,最后遍历path1和path2,两个人到达同一个KFC且两者之和最小的便是最短路程.
#include<stdio.h>
#include<string.h>
#include<queue>
#include<limits.h>
using namespace std;
int n,m;
char map[205][205];
int vis[205][205];
int d[4][2]={0,1,1,0,-1,0,0,-1};
struct node{
int x,y,step;
};
node path1[1001]; //存Y到每个@所需要的步数
node path2[1001]; //存M到每个@所需要的步数
int cnt;
int cnt1;
void Bfs(int x,int y,node path[]){
int i;
memset(vis,0,sizeof(vis));
queue<node>q;
node s,e;
s.x=x;
s.y=y;
s.step=0;
q.push(s);
while(!q.empty()){
s=q.front();
q.pop();
if(map[s.x][s.y]=='@'){
path[cnt++]=s;
}
for(i=0;i<4;i++){
int xx=s.x+d[i][0];
int yy=s.y+d[i][1];
if(xx<0||yy<0||xx>=n||yy>=m)
continue;
if(map[xx][yy]=='#')continue;
if(vis[xx][yy])continue;
vis[xx][yy]=1;
e.x=xx;
e.y=yy;
e.step=s.step+1;
q.push(e);
}
}
}
int main()
{
int i,j;
while(scanf("%d %d",&n,&m)!=EOF){
memset(path1,0,sizeof(path1));
memset(path2,0,sizeof(path2));
cnt=0;
for(i=0;i<n;i++){
scanf("%s",map[i]);
}
for(i=0;i<n;i++){
for(j=0;j<m;j++){
if(map[i][j]=='Y')
Bfs(i,j,path1); //Y到每个@
}
}
cnt1=cnt;
cnt=0;
for(i=0;i<n;i++){
for(j=0;j<m;j++){
if(map[i][j]=='M')
Bfs(i,j,path2); //M到每个@
}
}
int min=INT_MAX;
for(i=0;i<cnt1;i++){ //找到Y和M到同一个@所需要的最少步数
for(j=0;j<cnt;j++){
if(path1[i].x==path2[j].x
&&path1[i].y==path2[j].y){
if(11*(path1[i].step+path2[j].step)<min)
min=path1[i].step*11+path2[j].step*11;
}
}
}
printf("%d\n",min);
}
return 0;
}