ZOJ1649 营救Rescue (BFS)

题目链接

http://acm.zju.edu.cn/onlinejudge/showProblem.do?problemCode=1649

题意

Angel被抓了,并且被关在监狱里。监狱可以用一个NxM的矩阵来表示。监狱由NxM个方格表示,每个方格可能为墙壁、道路、警卫、她的朋友和她。angel的朋友可以向上、下、左、右四个方向走,走到为道路的方格需要时间1,走到有警卫的方格需要时间2(杀死警卫需要时间1)。从r到a至少需要多少时间?

题解

注意到题干是friends,所以r可能有多个,也就是说应该从a广搜到r。
用一个优先队列来实现广搜,将用时最少的放在队首。即用一个结构体node来存放a到达某个方格的状态。该结构体包含方格里的值,到该方格的时间,方格的坐标。

代码

#include <cstdio>
#include <cstring>
#include <queue>

using namespace std;

const int maxn=4e4+100;
struct node
{
    char v;
    int t,x,y;
}a[maxn];
char map[220][220];

int N,M,dir[4][2]={0,1,0,-1,1,0,-1,0},vis[220][220];
priority_queue<node> que;
bool operator<(const node &n1,const node &n2)
{
    return n1.t>n2.t;
}

bool valid(int x,int y)
{
    return map[x][y]!='#' && x<=N&&x>=1 && y<=M&&y>=1 && !vis[x][y];
}

void bfs()
{
    while(!que.empty())
    {
        que.pop();
    }
    for(int i=1;i<=N;i++)
        for(int j=1;j<=M;j++)
        if(map[i][j]=='a')
            que.push(node{'a',0,i,j}),vis[i][j]=1;
    while(!que.empty())
    {
        node tmp=que.top();que.pop();
        if(tmp.v=='r')
        {
            printf("%d\n",tmp.t);
            return;
        }
        for(int i=0;i<4;i++)
        {
            int fx=tmp.x+dir[i][0];
            int fy=tmp.y+dir[i][1];
            if(valid(fx,fy))
            {
                vis[fx][fy]=1;
                node now={map[fx][fy],tmp.t+1,fx,fy};
                now.t=map[fx][fy]=='x'?now.t+1:now.t;
                que.push(now);
            } 
        }
    }
    printf("Poor ANGEL has to stay in the prison all his life.\n");
}

int main()
{
    while(~scanf("%d%d",&N,&M))
    {
        memset(vis,0,sizeof(vis));
        for(int i=1;i<=N;i++)
            scanf("%s",map[i]+1);
        bfs();
    }
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值