BFS-Find a way HDU - 2612
题目:
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.
Input
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
Output
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.
Sample Input
4 4
Y.#@
…
.#…
@…M
4 4
Y.#@
…
.#…
@#.M
5 5
Y…@.
.#…
.#…
@…M.
#…#
Sample Output
66
88
66
题意:
两人要去同一个(肯德基)@相遇,问两人一共耗时最少是多少。
思路:
分别遍历两人到每个@的最短时间,再求出两人到每一个@的时间和的最小值即可。
#include<iostream>
#include<cstring>
#include<cmath>
#include<queue>
#include<algorithm>
#define inf 0x3f3f3f3f
using namespace std;
int n,m,i,j;
char mp[210][210];
bool vis[210][210];
int dir[4][2]={{1,0},{-1,0},{0,1},{0,-1}};
int ans1[210][210];
int ans2[210][210];
struct node
{
int x,y,step=0;
int N;
};
queue<node>Q;
void bfs(node n1)
{
vis[n1.x][n1.y]=true;
Q.push(n1);
while(!Q.empty())
{
node tmp1=Q.front();
node tmp2;
Q.pop();
for(int k=0;k<4;k++)
{
tmp2.x=tmp1.x+dir[k][0];
tmp2.y=tmp1.y+dir[k][1];
tmp2.step=tmp1.step+1;
tmp2.N=tmp1.N;
if(mp[tmp2.x][tmp2.y]=='#')
continue;
if(mp[tmp2.x][tmp2.y]=='@'&&!vis[tmp2.x][tmp2.y])//!vis[tmp2.x][tmp2.y]一开始没加!!!
{
if(tmp2.N==1) ans1[tmp2.x][tmp2.y]=tmp2.step;//坐标又写错了!!!!!
else ans2[tmp2.x][tmp2.y]=tmp2.step;
Q.push(tmp2);
vis[tmp2.x][tmp2.y]=true;//这两行入队和标记一开始也没写!
}
if(mp[tmp2.x][tmp2.y]=='.'&&!vis[tmp2.x][tmp2.y])
{
Q.push(tmp2);
vis[tmp2.x][tmp2.y]=true;//这里一不小心还写了个递归,今晚脑子不太好使
}
}
}
return;
}
int main()
{
while(cin>>n>>m){//第一发这个while还没加,加了以后就过了。没有连续输出??奇葩的数据
node n1,n2;
for(i=1;i<=n;i++)
for(j=1;j<=m;j++)
{
cin>>mp[i][j];
if(mp[i][j]=='Y')//记录起点
n1.x=i,n1.y=j,n1.N=1;
if(mp[i][j]=='M')
n2.x=i,n2.y=j,n2.N=2;
}
memset(vis,false,sizeof(vis));
memset(ans1,inf/2,sizeof(ans1));
memset(ans2,inf/2,sizeof(ans2));
bfs(n1);
memset(vis,false,sizeof(vis));//这里再求另一个起点最短路时别忘了重置标记数组
bfs(n2);
int ans=inf;
for(i=1;i<=n;i++)
{
for(j=1;j<=m;j++)
{
if(mp[i][j]=='@')
{
if(ans>ans1[i][j]+ans2[i][j])
ans=ans1[i][j]+ans2[i][j];
}
}
}
cout<<ans*11<<endl;
}
return 0;
}
总结:
- 求两个起点路程和的最小值跟双起点bfs又略有不同
- 写数组下标的时候想清楚
- 点要及时入队,数组要及时标记!
- if判断条件中别忘了去除已经标记过的点!