【搜索】HDU 2612 Find a way

【题目】http://acm.hdu.edu.cn/showproblem.php?pid=2612

【题意】有2个人要走到同一个@上见面,问他们走的距离和最小是多少。

【思路】两次bfs

注意bfs的vis标记要在for里面写,否则会让一些点从夫入队

【代码】

#include<bits/stdc++.h>
#define fuck(x) std::cout<<"["<<#x<<"->"<<x<<"]"<<endl;
using namespace std;
typedef long long ll;

const int M=2e5+5;
const int inf=1e9+5;

int tot;

char mp[505][505];
int vis[505][505];
int n,m;
int sx,sy,tx,ty;
int to[4][2]= {0,1,1,0,0,-1,-1,0};

struct node  // @@@
{
    int x,y,hans;
};
node hlfans[M];
map< pair<int,int>,int>mpp;

int ans=inf;

void bfs1()
{
    queue<node>q;
    node t{sx,sy,0};
    vis[sx][sy]=1;
    q.push(t);
    while(!q.empty())
    {
        t=q.front();
        q.pop();
        if(mp[t.x][t.y]=='@')
        {
            mpp[ {t.x,t.y}]=t.hans;
        }
        for(int i=0; i<4; i++)
        {
            if(t.x+to[i][0]>=n||t.y+to[i][1]>=m||t.y+to[i][1]<0||t.x+to[i][0]<0)
                continue;
            if(vis[t.x+to[i][0]][t.y+to[i][1]]==1)
                continue;
            if(mp[t.x+to[i][0]][t.y+to[i][1]]=='#')
                continue;
            q.push({t.x+to[i][0],t.y+to[i][1],t.hans+1});
            vis[t.x+to[i][0]][t.y+to[i][1]]=1;
            //更新vis要在这里,在上面更新会导致一些点重复入队.
        }
    }
}

int bfs2(int x,int y)
{
    queue<node>q;
    node t{x,y,0};
    vis[x][y]=1;
    q.push(t);
    while(!q.empty())
    {
        t=q.front();
        q.pop();
        if(mp[t.x][t.y]=='@')
        {
            if(mpp[ {t.x,t.y}]!=0)
                ans=min(ans,t.hans+mpp[ {t.x,t.y}]);
        }
        for(int i=0; i<4; i++)
        {
            if(t.x+to[i][0]>=n||t.y+to[i][1]>=m||t.y+to[i][1]<0||t.x+to[i][0]<0)
                continue;
            if(vis[t.x+to[i][0]][t.y+to[i][1]]==1)
                continue;
            if(mp[t.x+to[i][0]][t.y+to[i][1]]=='#')
                continue;
            q.push({t.x+to[i][0],t.y+to[i][1],t.hans+1});
            vis[t.x+to[i][0]][t.y+to[i][1]]=1;
        }
    }
    return inf;
}

int main()
{
    while(~scanf("%d%d",&n,&m))
    {
        mpp.clear();
        tot=0;
        ans=inf;
        for(int i=0; i<n; i++)
        {
            scanf("%s",mp[i]);
            for(int j=0; j<m; j++)
            {
                if(mp[i][j]=='Y')
                {
                    sx=i,sy=j;
                }
                else if(mp[i][j]=='M')
                {
                    tx=i,ty=j;
                }
            }
        }
        memset(vis,0,sizeof(vis));
        bfs1();
        memset(vis,0,sizeof(vis));
        bfs2(tx,ty);
        printf("%d\n",ans*11);
    }

    return 0;
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值