hdu 1242 Rescue (bfs+优先队列)

Rescue

                                                                             Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)

                                                                                                 Total Submission(s): 15639    Accepted Submission(s): 5673

题意:给出起点和终点走迷宫求最短路(注意起点有多个)

简单bfs(由于有多个起点所以上做下处理   从终点起去搜起点)+优先队列求出最优解

#include<iostream>
#include<cstdio>
#include<cstring>
#include<stack>
#include<queue>
using namespace std;
int n,m,ans,sx,sy;
char map[205][205];
int vis[205][205];
int dx[4]={-1,0,1,0};
int dy[4]={0,1,0,-1};
struct node{
    friend bool operator<(const node a,const node b)
    {
        return a.depth>b.depth;//大的数优先级低
    }
    int x,y,depth;
};

int bfs(int x,int y)
{
    int i;
    node a,t,p;
    priority_queue<node> q;
    a.x=x;
    a.y=y;
    a.depth=0;
    q.push(a);
    while(!q.empty())
    {
        t=q.top();
        q.pop();
        for(i=0;i<4;i++)
        {
            int xx,yy;
            p.x=t.x+dx[i];
            p.y=t.y+dy[i];
            if(p.x>=0&&p.x<n&&p.y>=0&&p.y<m&&!vis[p.x][p.y])
            {
                vis[p.x][p.y]=1;
                p.depth=t.depth+1;
                if(map[p.x][p.y]=='x')
                     p.depth++;
                if(map[p.x][p.y]=='r')
                    return p.depth;
                q.push(p);
            }
        }
    }
    return 0;
}

int main()
{
    char a;
    int i,j;
    while(cin>>n>>m)
    {
        memset(vis,0,sizeof(vis));
        for(i=0;i<n;i++)
            scanf("%s",&map[i]);
        for(i=0;i<n;i++)
            for(j=0;j<m;j++)
            {
                if(map[i][j]=='a')
                {
                    sx=i;
                    sy=j;
                    vis[i][j]=1;
                }
                if(map[i][j]=='#')
                    vis[i][j]=1;

            }
              ans=bfs(sx,sy);
              if(ans!=0)
           printf("%d\n",ans);
           else
           cout<<"Poor ANGEL has to stay in the prison all his life."<<endl;

    }
    return 0;
}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值