您的位置:首页 > 其它

BFS台州1335营救天使

2016-03-30 21:01 281 查看
点击打开链接  题目链接

本题需要用到优先队列 

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

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

比如:

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;

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  bfs 搜索