ZOJ1649 营救Rescue (BFS)

来源:互联网 发布:ifashion淘宝 编辑:程序博客网 时间:2024/05/12 16:11

题目链接

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;}
原创粉丝点击