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

#include 
#include 
#include 
#include 
#include 
#include 
#include 
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;
}

你可能感兴趣的:(kuangbin)