hdu 2612 Find a way【BFS】

82 篇文章 0 订阅
23 篇文章 0 订阅

题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=2612
题意:y和m要在kfc见面,问你能否选择一家kfc使得y和m到那里的距离最短
解析:两个人都跑一遍bfs,然后枚举每家kfc,找出最优的即可

#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <cmath>
#include <queue>
using namespace std;
const int inf = 0x7fffffff;
int dx[] = {0,1,-1,0};
int dy[] = {1,0,0,-1};
int vis[205][205];
int step1[205][205];
int step2[205][205];
int n,m;
char a[205][205];
struct node
{
    int x,y;
    int step;
    node() {}
    node(int _x,int _y,int _step)
    {
        x = _x;
        y = _y;
        step = _step;
    }
};
void bfs(int sx,int sy,int step[205][205])
{
    memset(vis,0,sizeof(vis));
    queue<node>q;
    q.push(node(sx,sy,0));
    while(!q.empty())
    {
        node now = q.front();
        q.pop();
        if(a[now.x][now.y]=='@')
        {
            if(step[now.x][now.y])
                step[now.x][now.y] = min(step[now.x][now.y],now.step);
            else
                step[now.x][now.y] = now.step;
        }
        for(int i=0;i<4;i++)
        {
            int tx = now.x+dx[i];
            int ty = now.y+dy[i];
            if(tx<0 || tx>=n || ty<0 || ty>=m)
                continue;
            if(a[tx][ty]=='#' || vis[tx][ty])
                continue;
            vis[tx][ty] = 1;
            q.push(node(tx,ty,now.step+1));
        }
    }
}
int main()
{
    while(~scanf("%d %d",&n,&m))
    {
        int x1,y1,x2,y2;
        for(int i=0;i<n;i++)
        {
            scanf("%s",a[i]);
            for(int j=0;j<m;j++)
            {
                if(a[i][j]=='Y')
                {
                    x1 = i;
                    y1 = j;
                }
                if(a[i][j]=='M')
                {
                    x2 = i;
                    y2 = j;
                }
            }
        }
        memset(step1,0,sizeof(step1));
        memset(step2,0,sizeof(step2));
        bfs(x1,y1,step1);
        bfs(x2,y2,step2);
        int ans = inf;
        for(int i=0;i<n;i++)
        {
            for(int j=0;j<m;j++)
            {
                if(a[i][j] == '@')
                {
                    if(step1[i][j] && step2[i][j])
                        ans = min(ans,step1[i][j]+step2[i][j]);
                }
            }
        }
        printf("%d\n",ans*11);
    }
    return 0;
}
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值