ZOJ1649-拯救天使

题意就是说“@”被困住了,要求“r”去拯救,“x”表示可以走,但是要2个单位时间,而“.”表示可以走,只要1个单位时间,“#”表示不能走。求能否到达,输出最短的单位时间,不能就按题意输出。
题目链接:http://acm.zju.edu.cn/onlinejudge/showProblem.do?problemCode=1649
思路:这个就是一个迷宫问题,通过BFS+优先队列来解。

代码:

#include//优先队列+记忆化搜索+广搜
#include
#include
using namespace std;
int n,m;
int xx[4]= {1,0,-1,0};
int yy[4]= {0,1,0,-1};
char map[210][210];
int vis[210][210];
struct point //自定义最小优先队列
{
    int x,y,time;
    friend bool operator<(point a,point b)
    {
            return a.time>b.time;
    }
};
int BFS(point start)
{
    priority_queue q;
    q.push(start);
    point now,next;
    int i;
    while(!q.empty())
    {
        now=q.top();
        q.pop();
        for(i=0; i<4; i++)
        {
            next.x=now.x+xx[i];
            next.y=now.y+yy[i];
            if(map[next.x][next.y]=='r')
            {
                next.time=now.time+1;
                while(!q.empty())
                    q.pop();
                return next.time;
            }
            if(next.x>=0&&next.y>=0&&next.x
            if(map[next.x][next.y]!='#'&&!vis[next.x][next.y])
            {
                if(map[next.x][next.y]=='x')
                {
                    vis[next.x][next.y]=1;
                    next.time=now.time+2;
                    q.push(next);
                }
                else
                {
                    vis[next.x][next.y]=1;
                    next.time=now.time+1;
                    q.push(next);
                }
            }
        }
    }
    return -1;
}
int main()
{
    int i,j,t;
    point s;
    while(scanf("%d%d",&n,&m)!=-1)
    {
        for(i=0; i
        {
            scanf("%s",map[i]);
            for(j=0; j
            {
                if(map[i][j]=='a')
                {
                    s.x=i;
                    s.y=j;
                    s.time=0;
                }
            }
        }
        memset(vis,0,sizeof(vis));
        t=BFS(s);
        if(t==-1)
            printf("Poor ANGEL has to stay in the prison all his life.\n");
        else
            printf("%d\n",t);
    }
    return 0;
}

你可能感兴趣的:(BFS,算法)