【BFS】HDU 2612 Find a way

21 篇文章 0 订阅

Problem Description

给你一个n,m的矩阵,里面有Y.#@M分别代表小明家,路,墙,KFC,小红家。问你那个KFC使得到两个人家距离最近

代码:一开始,先找@,BFS每个@找到Y,M求和,发现超时,换了一种方法,先找Y,M分别BFS这两个,找到距离所有的KFC的距离。后面暴力求最小(每一步11分钟)

#include<algorithm>
#include<cstdio>
#include<queue>
#include<cstring>
using namespace std;
struct node
{
    int x, y;
};
queue<node> q;
char Map[250][250];//矩阵
int vis[250][250][2], n, m;//标记&路径,行,列。
int X[5] = {-1, 0, 1, 0};//各个方向
int Y[5] = {0, 1, 0, -1};
int judge(int x1, int y1, int flag)//判断能不能走
{
    if(x1 >= 0 && y1 >= 0 && x1 < n && y1 < m && Map[x1][y1] != '#' && !vis[x1][y1][flag])
    return 1;
    else return 0;
}
void BFS(node u, int flag)//flag用于区分Y,M
{
    q.push(u);
    vis[u.x][u.y][flag] = 1;//最开始设为1,后面-1就可以了
    node t;
    while(!q.empty())
    {
        t = q.front();
        q.pop();
        int xx = t.x, yy = t.y;
        for(int i = 0; i < 4; i++)
        {
            if(judge(xx + X[i], yy + Y[i], flag))
            {
                vis[xx + X[i]][yy + Y[i]][flag] = vis[xx][yy][flag] + 1;
                u.x = xx + X[i]; u.y = yy + Y[i];
                q.push(u);
            }
        }
    }
}
int main()
{
    int i, j, top;
    node c[2], tem;
    while(~scanf("%d %d", &n, &m))
    {
        top = 0;
        memset(vis, 0, sizeof(vis));
        for(i = 0; i < n; i++)
        {
            scanf("%s", Map[i]);
            for(j = 0; j < m; j++)
            {
                //记录Y,M的下标
                if(Map[i][j] == 'Y' || Map[i][j] == 'M')
                {
                    tem.x = i; tem.y = j;
                    c[top++] = tem;
                }
            }
        }
        for(i = 0; i < top; i++)
        {
            BFS(c[i], i);//i用于区分Y,M
        }
        int ans = 50000;
        for(i = 0; i < n; i++)
        {
            for(j = 0; j < m; j++)
            {
                if(Map[i][j] == '@' && vis[i][j][0] && vis[i][j][1])//代表这个KFC两个人都可以到达,求最小
                {
                    ans = min(vis[i][j][0] + vis[i][j][1] - 2, ans);
                }
            }
        }
        printf("%d\n", ans * 11);
    }
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值