[kuangbin带你飞]专题一 简单搜索- N - Find a way

#include <iostream>
#include <cmath>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <queue>
#include <map>
using namespace std;
#define INF 0x3f3f3f
int gcd(int a, int b) {return b==0 ? a:gcd(b,a%b);}

int n, m;
int x1, x2;
int sy1, y2;
char s[220][220];
int dis1[220][220];
int dis2[220][220];
int vis[220][220];
int xx[] = {0,0,-1,1};
int yy[] = {-1,1,0,0};
struct node
{
    int x, y, step;
    node(){};
    node(int x, int y, int step):x(x),y(y),step(step){}
};
void bfs()
{   
    memset(vis,0,sizeof(vis));
    queue<node>q;
    q.push((node){x1,sy1,0});
    vis[x1][sy1] = 1;
    dis1[x1][sy1] = 0;
    while(!q.empty())
    {
        node p = q.front(); q.pop();
        dis1[p.x][p.y] = p.step;
        for(int i = 0; i < 4; i++)
        {
            int tx = p.x+xx[i];
            int ty = p.y+yy[i];
            if(tx<1||ty<1||tx>n||ty>m||vis[tx][ty]||s[tx][ty]=='#') continue;
            vis[tx][ty] = 1;
            q.push((node){tx,ty,p.step+1});
        }
    }
    
    memset(vis,0,sizeof(vis));
    q.push((node){x2,y2,0});
    vis[x2][y2] = 1;
    dis2[x2][y2] = 0;
    while(!q.empty())
    {
        node p = q.front(); q.pop();
        dis2[p.x][p.y] = p.step;
        for(int i = 0; i < 4; i++)
        {
            int tx = p.x+xx[i];
            int ty = p.y+yy[i];
            if(tx<1||ty<1||tx>n||ty>m||vis[tx][ty]||s[tx][ty]=='#') continue;
            vis[tx][ty] = 1;
            q.push((node){tx,ty,p.step+1});
        }
    }
}

int main()
{
    while(~scanf("%d %d", &n, &m)&&n&&m)
    {
        for(int i = 1; i <= n; i++) scanf("%s", s[i]+1);
        int minn = INF;
        for(int i = 1; i <= n; i++)
        {
            for(int j = 1; j <= m; j++)
            {
                if(s[i][j]=='Y'){
                    x1 = i; sy1 = j;
                }
                if(s[i][j]=='M'){
                    x2 = i; y2 = j;
                }
            }
        }
        bfs();
        for(int i = 1; i <= n; i++)
        {
            for(int j = 1; j <= m; j++)
            {
                if(s[i][j]=='@'){
                    minn = min(minn,dis1[i][j]+dis2[i][j]);
                }
            }
        }
        printf("%d\n", minn*11);
    }
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值