BFS台州1335营救天使

点击打开链接  题目链接

本题需要用到优先队列 

优先队列:不同于普通的队列,优先队列是按照优先级高的先输出

若是不用优先队列:则会有数据出现错误

比如:

3 3
#.r
#.x
#a#

次组数据是没有按照优先队列 则搜索的时间为4而不是3了  

4 3

..r

.#x

.#x

.ax

这一组同样会得到7而不是6

优先队列不懂得可以去下面的链接看看详细介绍

点击打开链接

广搜:

#include <cstdio>
#include <cstring>
#include <iostream>
#include <queue>
using namespace std;
int go[4][2] = {{0,-1},{-1,0},{1,0},{0,1}};
char map[201][201];
int vis[201][201];
int n, m, ex, ey;
struct point
{
    int x, y;
    int step;
    friend bool operator < (point a,point b)
    {
        return a.step > b.step;   ///优先步数小的输出
    }
}p;
int bfs(int x1,int y1)
{
    p.x = x1,p.y = y1,p.step = 0;
    priority_queue<point>q;
    point current, next;
    q.push(p);
    vis[x1][y1] = 1;
    while(!q.empty())
    {
        current = q.top();
        q.pop();
        for(int i = 0; i < 4; i++)
        {
            next.x = current.x + go[i][0];
            next.y = current.y + go[i][1];


            if(map[next.x][next.y]!='#'&&next.x>=0&&next.x<n&&next.y>=0&&next.y<m&&vis[next.x][next.y]!=1)
            {
                if(map[next.x][next.y]=='a')
                {
                       next.step = current.step + 1;
                       return next.step;
                }
                if(map[next.x][next.y]=='x')
                {
                        vis[next.x][next.y] = 1;
                        next.step = current.step + 2;
                        q.push(next);
                }
                else
                {
                    vis[next.x][next.y] = 1;
                    next.step = current.step + 1;
                    q.push(next);
                }


            }
        }
    }
    return -1;
}
int main()
{
    while(cin >> n >> m)
    {
        int ans;
        memset(vis,0,sizeof(vis));
        for(int i = 0; i < n; i++)
            for(int j = 0; j < m; j++)
                cin >> map[i][j];
        for(int i = 0; i < n; i++)
            for(int j = 0; j < m; j++)
            {
                if(map[i][j]=='r')
                {
                    ex = i;
                    ey = j;
                    map[i][j] = '#';


                }
            }
        ans = bfs(ex,ey);
        if(ans!=-1)
            cout << ans << endl;
        else
            cout << "Poor ANGEL has to stay in the prison all his life." << endl;
    }
    return 0;


}


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值