Description
Input
Output
Sample Input
4 4 Y.#@ .... .#.. @..M 4 4 Y.#@ .... .#.. @#.M 5 5 Y..@. .#... .#... @..M. #...#
Sample Output
66 88 66
这道题大概题意:输入地图, # :表示墙; . :表示路; Y和M :分别表示两个人; @ :表示KFC. 两个人都要去同一家KFC,但是地图上有很多KFC,输出最短的路程和.(注:每步的路程是11)
思路:以两个人为基准点先后BFS,每次找到KFC的位置后分别存入path1和path2,最后遍历path1和path2,两个人到达同一个KFC且两者之和最小的便是最短路程.
#include
#include
#include
#include
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));
queueq;
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