HDU 2602 Find a way BFS搜索

题意:找到总时间最少的KFC

分析:两遍BFS 找KFC比较一下

注:有些地方的KFC可能到达不了,wa了一次

#include <iostream>
#include <cstdio>
#include <algorithm>
#include <string>
#include <cmath>
#include <set>
#include <queue>
#include <cstring>
using namespace std;
typedef long long LL;
const int maxn=200+5;
const int INF=0x3f3f3f3f;
char s[maxn][maxn];
int a[maxn][maxn];
int b[maxn][maxn];
int n,m;
int dx[4]={0,0,-1,1};
int dy[4]={-1,1,0,0};
struct Point
{
    int x,y;
    Point(){}
    Point(int p,int q)
    {
       x=p,y=q;
    }
} o,t;
queue<Point>Y,M;
vector<Point>v;
int main()
{
    while(~scanf("%d%d",&n,&m))
    {
        v.clear();
        memset(a,-1,sizeof(a));
        memset(b,-1,sizeof(b));
        for(int i=1;i<=n;++i)
         scanf("%s",s[i]+1);
        for(int i=1;i<=n;++i)
        {
           for(int j=1;j<=m;++j)
           {
              if(s[i][j]=='@')v.push_back(Point(i,j));
              else if(s[i][j]=='Y')Y.push(Point(i,j)),a[i][j]=0;
              else if(s[i][j]=='M')M.push(Point(i,j)),b[i][j]=0;
           }
        }
        while(!Y.empty())
        {
            o=Y.front();
            Y.pop();
            for(int i=0;i<4;++i)
            {
               t.x=o.x+dx[i];
               t.y=o.y+dy[i];
               if(t.x<1||t.x>n||t.y<1||t.y>m)continue;
               if(s[t.x][t.y]=='#'||a[t.x][t.y]>=0)continue;
               a[t.x][t.y]=a[o.x][o.y]+1;
               Y.push(t);
            }
        }
         while(!M.empty())
        {
            o=M.front();
            M.pop();
            for(int i=0;i<4;++i)
            {
               t.x=o.x+dx[i];
               t.y=o.y+dy[i];
               if(t.x<1||t.x>n||t.y<1||t.y>m)continue;
               if(s[t.x][t.y]=='#'||b[t.x][t.y]>=0)continue;
               b[t.x][t.y]=b[o.x][o.y]+1;
               M.push(t);
            }
        }
        int ans=INF;
        for(int i=0;i<v.size();++i)
        {
            int x=v[i].x,y=v[i].y;
            if(a[x][y]==-1||b[x][y]==-1)continue;
            ans=min(ans,a[x][y]+b[x][y]);
        }
        printf("%d\n",ans*11);
    }
    return 0;
}
View Code

 

你可能感兴趣的:(HDU 2602 Find a way BFS搜索)