hdu 1242 优先级队列 bfs

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

原帖地址: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;
}


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值