hdu 1242 Rescue (BFS+优先队列)

题目地址:http://acm.hdu.edu.cn/showproblem.php?pid=1242

 

 

这道题目我是用BFS+优先队列做的。听说只用bfs会超时。

 

因为这道题有多个营救者,所以我们从被营救者开始bfs,找到最近的营救者就是最短时间。

 

先定义一个结构体,存放坐标x和y,还有到达当前点(x,y)消耗的时间。


struct node {
    int x,y;
    int time;
    friend bool operator < (const node &a,const node &b){
        //时间少的放在队列前面
        return a.time>b.time;
    }
};

注意时间少的先出列。

 

重点讲一下bfs的过程,当前格子命名为now,走过的下一个格子命名为next,先将起点赋值给now然后入队。



now.x=x;
    now.y=y;
    now.time=0;//源点走到源点时间初始为0
    vis[now.x][now.y]=1;
    que.push(now);//源点入队

之后只要队列不为空,就取出队列的头节点,判断是否为终点也就是任意一个r,如果是r,则返回到达当前节点所需时间即:now.time;若不是r,那接下来把now的四个方向全部遍历一百,如果不是墙就将其加入队列,并且把当前time更新:next.time=now.time+delta。delta的值遇到x就是2,否则是1。一直循环直到que.top出来的坐标代表的是r。

 

若队列为空即找完了全图都没找到r,那就返回-1,代表无法解救。

 

好了贴个代码:

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

using namespace std;

int n,m;
int vis[202][202];
char map[202][202];
int dir[4][2]={{1,0},{-1,0},{0,1},{0,-1}};

struct node {
    int x,y;
    int time;
    friend bool operator < (const node &a,const node &b){
        //时间少的放在队列前面
        return a.time>b.time;
    }
};

int can_go(int x,int y){
    if(x>=0&&x<n&&y>=0&&y<m&&map[x][y]!='#'){
        return 1;
    }
    else return 0;
}

int bfs(int x,int y){
    int i;
    node now,next;
    priority_queue<node>que;
    memset(vis,0,sizeof(vis));
    now.x=x;
    now.y=y;
    now.time=0;//源点走到源点时间初始为0
    vis[now.x][now.y]=1;
    que.push(now);//源点入队
    while(!que.empty()){
        now=que.top();
        que.pop();
        if(map[now.x][now.y]=='r'){
            return now.time;
        }
        for(i=0;i<4;i++){
            next.x=now.x+dir[i][0];
            next.y=now.y+dir[i][1];
            if(can_go(next.x,next.y)&&!vis[next.x][next.y]){
                vis[next.x][next.y]=1;
                if(map[next.x][next.y]=='x'){
                    next.time=now.time+2;
                }
                else {
                    next.time=now.time+1;
                }
                que.push(next);
            }
        }
    }
    return -1;
}

int main()
{
    int ans;
    int i,j;
    int x,y;
    while(scanf("%d%d",&n,&m)!=EOF){
        for(i=0;i<n;i++){
            scanf("%s",map[i]);
        }
        for(i=0;i<n;i++)
            for(j=0;j<m;j++)
                if(map[i][j]=='a'){
                    x=i;
                    y=j;
                    break;
                }
        ans=bfs(x,y);
        if(ans==-1){
            printf("Poor ANGEL has to stay in the prison all his life.\n");
        }
        else {
            printf("%d\n",ans);
        }
    }
    return 0;
}



  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值