HDU2612.Find a way(BFS)

思路:分别从Y和M点广搜@点,将所有的@点记录下来,在比较到达每个@点Y和M需要步数的最小值。并且要注意有些KFC是无法访问到的。

#include
#include
#include
#include
#include
using namespace std;

struct Point
{
    int x,y;
} tmp,tmp1;

queueq;
int n,m;

int visy[205][205];
int vism[205][205];
char str[205][205];
int dx[4] = {-1, 1, 0, 0};
int dy[4] = {0, 0, 1, -1,};

void BFS(Point p,int vis[205][205])
{
    Point t,t1;
    while(!q.empty())
    {
        q.pop();
    }
    memset(vis,0,sizeof(vis));
    q.push(p);
    vis[p.x][p.y] = 1;
    while(!q.empty())
    {
        t = q.front();
        q.pop();
        for(int i = 0; i < 4; i++)
        {
            t1.x = t.x + dx[i];
            t1.y = t.y + dy[i];
            if(!vis[t1.x][t1.y] && str[t1.x][t1.y] != '#' && t1.x >=0 && t1.x < n && t1.y >=0 && t1.y < m )
            {
                vis[t1.x][t1.y] = vis[t.x][t.y] + 1;
                q.push(t1);
                //printf("%d %d %d\n",t1.x,t1.y,vis[t1.x][t1.y]);
            }
        }
    }
}

int main()
{
    while(~scanf("%d%d",&n,&m))
    {
        memset(str,'0',sizeof(str));
        memset(vism,0,sizeof(vism));
        memset(visy,0,sizeof(visy));
        for(int i = 0; i < n; i++)
            scanf("%s",str[i]);
        for(int i = 0; i < n; i++)
            for(int j = 0; j < m; j++)
            {
                if(str[i][j] == 'Y')
                {
                    tmp.x = i;
                    tmp.y = j;
                }
                if(str[i][j] == 'M')
                {
                    tmp1.x = i;
                    tmp1.y = j;
                }
            }
        BFS(tmp,visy);
        BFS(tmp1,vism);
        int ans = 1000000000;
        int Min = 0;
        for(int i = 0; i < n; i++)
            for(int j = 0; j < m; j++)
            {
                if(str[i][j] == '@')
                {
                    Min = visy[i][j] + vism[i][j] - 2;
                    //printf("%d %d\n",ans,Min);
                    if(Min > 0)//如果是0的话就不进行比较
                        ans = min(ans,Min);
                }
            }
        printf("%d\n",ans*11);
    }
    return 0;
}

 

你可能感兴趣的:(简单搜索)