hdu 2612 Find a way bfs

来源:互联网 发布:java继承和多态的作用 编辑:程序博客网 时间:2024/06/05 17:42
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 4Y.#@.....#..@..M4 4Y.#@.....#..@#.M5 5Y..@..#....#...@..M.#...#
Sample Output
668866


  思路  两次bfs遍历Y与M到每个点的距离, 对于每个@,相加Y与M离@的距离,取最小值

 刚开始 我先找@的位置然后遍历从Y M和的最短距离 超时了,,

     后来写成两次bfs遍历Y与M到每个点的距离, 对于每个@,相加Y与M离@的距离,一直wa,我初始话错了  应该在没遍历之前初始化为无限大

#include<iostream>#include<queue>#include<cstring>#include<algorithm>using namespace std;const int M=300;const int inf=0x3f3f3f3f;char maps[M][M];int dis1[M][M];int dis2[M][M];int dis[M][M];int n,m;int yx,yy;int mx,my;int dx[4]={1,-1,0,0};int dy[4]={0,0,1,-1};typedef pair<int,int>P;void bfs(int x,int y,int (&dis)[M][M]){    memset(dis,inf,sizeof(dis));    P a;    a.first=x;    a.second=y;    queue<P> q;    q.push(a);    dis[x][y]=0;    while(!q.empty())    {        P a=q.front();        q.pop();        for(int i=0;i<4;i++)        {            int nx=a.first+dx[i],ny=a.second+dy[i];            if(nx>=0&&nx<n&&ny>=0&&ny<m&&maps[nx][ny]!='#'&&dis[nx][ny]==inf)            {                dis[nx][ny]=dis[a.first][a.second]+1;                q.push(P(nx,ny));            }        }    }}int main(){    while(cin>>n>>m)    {        memset(maps,0,sizeof(maps));        memset(dis1,inf,sizeof(dis1));        memset(dis2,inf,sizeof(dis2));        for(int i=0;i<n;i++)        {            for(int j=0;j<m;j++)            {                cin>>maps[i][j];                if(maps[i][j]=='Y')                    yx=i,yy=j;                if(maps[i][j]=='M')                    mx=i,my=j;            }        }        bfs(yx,yy,dis1);        bfs(mx,my,dis2);        int ans=0x3f3f3f3f;        for(int i=0;i<n;i++)            for(int j=0;j<m;j++)        {            if(maps[i][j]=='@')            {                ans=min(ans,dis1[i][j]+dis2[i][j]);            }        }        cout<<ans*11<<endl;    }    return 0;}