BFS——1242 Rescue

1242 Rescue

请添加图片描述

文章目录


题意:

在这里插入图片描述
解释如下:

a : 终 点 {\color{red}a:终点} a
r : 起 点 {\color{red}r:起点} r
. : 路 {\color{red}.:路} .:
# : 障 碍 {\color{red}\#:障碍} #
x : 敌 人 ( 需 要 花 一 个 单 位 时 间 打 败 ) {\color{red}x:敌人(需要花一个单位时间打败)} x:()

输出从起点到终点的最小步数,如果不存在路径,输出"Poor ANGEL has to stay in the prison all his life."。

思路:

我们在拓展时,如果一个点是敌人,则会导致我们需要花2步才能走到这个点,这将导致 BFS 每次出队的不一定是队列中步数最小的点,所以我们要用一个优先队列代替队列,使得每次出队的都是最小步数的点这一性质。

特别的,关于重载:

struct Node{
    int x,y,step;
    bool operator<(const Node &a)const
    {
        return a.step < step;
    }
};

AC代码:
在这里插入图片描述

#include<bits/stdc++.h>

typedef long long ll;

const int N = 2e2+10,M = 2e4+10,INF = 0x3f3f3f3f,mod = 1e9+7;
struct Node{
    int x,y,step;
    bool operator<(const Node &a)const
    {
        return a.step < step;
    }
};

char a[N][N];
int n,m,start_x,start_y,end_x,end_y;
int ne[4][2] = {0,1,1,0,0,-1,-1,0};
bool book[N][N];

bool OK(int x,int y)
{
    if(x<1||y<1||x>n||y>m||book[x][y]||a[x][y]=='#')return false;
    return true;
}

void bfs()
{
    memset(book,false,sizeof book);
    std::priority_queue<Node> que;
    que.push({start_x,start_y,0});
    book[start_x][start_y] = true;
    while(!que.empty())
    {
        auto temp = que.top();
        que.pop();
        if(temp.x == end_x && temp.y == end_y)
        {
            std::cout<<temp.step<<'\n';
            return;
        }
        for(int i = 0 ; i < 4 ; i++)
        {
            int tx = temp.x + ne[i][0];
            int ty = temp.y + ne[i][1];
            if(!OK(tx,ty))continue;
            if(a[tx][ty]=='x')book[tx][ty] = true,que.push({tx,ty,temp.step+2});
            else book[tx][ty] = true,que.push({tx,ty,temp.step+1});
        }
    }
    std::cout<<"Poor ANGEL has to stay in the prison all his life.\n";
}

int main()
{
//    std::ios::sync_with_stdio(false);
//    std::cin.tie(nullptr);
//    std::cout.tie(nullptr);
    while(std::cin>>n>>m)
    {
        for(int i = 1 ; i <= n ; i++)std::cin>>(a[i]+1);
        for(int i = 1 ; i <= n ; i++)
            for(int j = 1 ; j <= m ; j++)
                if(a[i][j]=='r')start_x = i,start_y = j;
                else if(a[i][j]=='a')end_x = i,end_y = j;
        bfs();
    }
    return 0;
}

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值