双BFS问题,就是用两遍BFS
题目描述
Pass a year learning in Hangzhou, yifenfei arrival hometown Ningbo at finally. Leave Ningbo one year, yifenfei have many people to meet. Especially a good friend Merceki.
Yifenfei’s home is at the countryside, but Merceki’s home is in the center of city. So yifenfei made arrangements with Merceki to meet at a KFC. There are many KFC in Ningbo, they want to choose one that let the total time to it be most smallest.
Now give you a Ningbo map, Both yifenfei and Merceki can move up, down ,left, right to the adjacent road by cost 11 minutes.
输入
The input contains multiple test cases.
Each test case include, first two integers n, m. (2<=n,m<=200).
Next n lines, each line included m character.
‘Y’ express yifenfei initial position.
‘M’ express Merceki initial position.
‘#’ forbid road;
‘.’ Road.
‘@’ KCF
输出
For each test case output the minimum total time that both yifenfei and Merceki to arrival one of KFC.You may sure there is always have a KFC that can let them meet.
样例输入
4 4
Y.#@
....
.#..
@..M
4 4
Y.#@
....
.#..
@#.M
5 5
Y..@.
.#...
.#...
@..M.
#...#
样例输出
66
88
66
分析
双BFS问题,就是用两遍BFS,求加和
#include"stdio.h"
#include"string.h"
#include"queue"
#define inf 99999
char map[201][201];//地图
int visit[201][201];
int dis[201][201][2];
using namespace std;
int n,m,flag;
int dir[4][2]={1,0, -1,0, 0,1, 0,-1};
struct point
{
int x,y;
int step;//走的步数
};
int judge(int x,int y)
{//判断是否越界
if(x>=0&&x<n&&y>=0&&y<m)
return 1;
return 0;
}
void bfs(int x,int y)
{
int i;
memset(visit,0,sizeof(visit));
queue<point>q;
point cur,next;
cur.x=x;
cur.y=y;
cur.step=0;
visit[x][y]=1;
q.push(cur);
while(!q.empty())
{
next=q.front();
q.pop();
for(i=0;i<4;i++)
{
cur.x=next.x+dir[i][0];
cur.y=next.y+dir[i][1];
cur.step=next.step+1;
if(judge(cur.x,cur.y))
{
if(map[cur.x][cur.y]!='#'&&visit[cur.x][cur.y]==0)//注意不能是map【】【】==''.'
{
visit[cur.x][cur.y]=1;
if(map[cur.x][cur.y]=='@')
dis[cur.x][cur.y][flag]=cur.step;
q.push(cur);
}
}
}
}
}
int main()
{
int i,j,k;
while(scanf("%d%d",&n,&m)!=EOF)
{
k=inf;
for(i=0;i<n;i++)
for(j=0;j<m;j++)
{
dis[i][j][0]=inf;
dis[i][j][1]=inf;
}
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')
{
flag=0;
bfs(i,j);
}
if(map[i][j]=='M')
{
flag=1;
bfs(i,j);
}
}
for(i=0;i<n;i++)
for(j=0;j<m;j++)
if(map[i][j]=='@'&&k>dis[i][j][0]+dis[i][j][1])
{//BFS用两次
k=dis[i][j][0]+dis[i][j][1];
}
printf("%d\n",11*k);
}
return 0;
}