hdu 1242 rescue (优先队列 bfs)

题意: 公主被关在 a位置 她的朋友在r位置

         路上x位置有恶魔 

         遇上恶魔花费2 时间 否在时间花费 1 时间

         问 最短多少时间 找到公主

 

思路: bfs+ 优先队列(时间短的先出列)

 

#include<cstdio>

#include<cstring>

#include<cmath>

#include<queue>

#include<iostream>

#include<algorithm>

using namespace std;

char mat[300][300];

int vis[300][300];

struct Node

{

    int x,y,coun;

    friend bool operator < (Node a,Node b){ return a.coun>b.coun; }  //小的先出列

};

int sx,sy,ex,ey;

int op[4][2]={1,0,-1,0,0,1,0,-1};

int n,m;

int ans;

bool fit(Node a)

{

    if(0<=a.x&&a.x<n&&0<=a.y&&a.y<m&&vis[a.x][a.y]==0&&mat[a.x][a.y]!='#') return true;

    return false;

}

void bfs()

{

    priority_queue<Node> q;

    Node f;

    f.x=sx;

    f.y=sy;

    f.coun=0;

    q.push(f);

    while(!q.empty())

    {

        Node now=q.top();

        q.pop();

        vis[now.x][now.y]=1;

        if(mat[now.x][now.y]=='r') {ans=now.coun;break;}

        for(int i=0;i<4;i++)

        {

            Node next;

            next.x=now.x+op[i][0];

            next.y=now.y+op[i][1];

            if(fit(next))

            {

                if(mat[next.x][next.y]=='.'||mat[next.x][next.y]=='r')

                next.coun=now.coun+1;

                else if(mat[next.x][next.y]=='x')

                    next.coun=now.coun+2;

                q.push(next);

            }

        }

    }

}

int main()

{

    int i,j,k;

    while(scanf("%d%d",&n,&m)!=EOF)

    {

        ans=-1;

        memset(vis,0,sizeof(vis));

        for(i=0;i<n;i++)

        {

            scanf("%s",mat[i]);

            for(j=0;j<m;j++)

            {

                if(mat[i][j]=='a') {sx=i;sy=j;}

            }

        }

        bfs();

        if(ans>-1)

        printf("%d\n",ans);

        else printf("Poor ANGEL has to stay in the prison all his life.\n");

    }

    return 0;

}

 

你可能感兴趣的:(优先队列)