hdu 1242 优先级队列 bfs

来源:互联网 发布:网络教育 统考 编辑:程序博客网 时间:2024/05/17 22:47

以为终点只有一个,起点有很多,可以逆向思维,从终点找到最近的起点即可.

原帖地址:http://blog.sina.com.cn/s/blog_87d81ad00100v8jx.html

#include <iostream>#include <cstdio>#include <cstdlib>#include <cstring>#include <algorithm>#include <cmath>#include<queue>using namespace std;const int MAX=200;char map[MAX][MAX];bool vis[MAX][MAX];int dir[4][2]={1,0,0,1,-1,0,0,-1},sx,sy;//之前没有这样定义方向的,写的时候居然写错了,找了半天错int n,m,t;struct node{    int x,y;    int step;    bool operator <(const node t)const    {            return step > t.step;//从小到大,小的优先级最高,详细请看我的另一篇:优先级队列 归纳    }};node start;void bfs()//里面没有递归,算是很简单的搜索了吧{    int i;    priority_queue<node>Q;    node p;    start.x=sx; start.y=sy; start.step=0;    Q.push(start);    vis[start.x][start.y]=true;    while(!Q.empty())    {        node q=Q.top();        Q.pop();        for(i=0;i<4;i++)        {            int xx,yy;            xx=q.x+dir[i][0]; yy=q.y+dir[i][1];            if(yy>=0 && yy<m && xx>=0 && xx<n && map[xx][yy]!='#' && !vis[xx][yy])            {                vis[xx][yy]=true;                if(map[xx][yy]=='r')                {                    t=q.step+1; return ;                }                p.x=xx; p.y=yy;                if(map[p.x][p.y]=='x')                {                    p.step=q.step+2;                }                else p.step=q.step+1;                Q.push(p);            }        }    }}int main(){    freopen("in.txt", "r", stdin);    //freopen("out.txt", "w", stdout);    int i,j;    while(cin>>n>>m)    {        for(i=0;i<n;i++)           for(j=0;j<m;j++)           {               cin>>map[i][j];               if(map[i][j]=='a') { sx=i; sy=j; }           }        /*本来担心读入是数字,后面读入字符需要getchar()的,所以测试了一下        for(i=0;i<n;i++)        {            for(j=0;j<m;j++) cout<<map[i][j];            cout<<endl;        }        */        t=-1;        memset(vis,false,sizeof(vis));        bfs();        //cout<<t<<endl;        if(t!=-1) cout<<t<<endl;        else cout<<"Poor ANGEL has to stay in the prison all his life."<<endl;    }    return 0;}


原创粉丝点击