hdu 1242 Rescue

  题目大意就是给你一个字符矩阵,找出r到达a的需要使用的最短时间。没走一步花掉单位1的时间,如果进过x,就多花费单位1的时间。如果r无法达到a,输出"Poor ANGEL has to stay in the prison all his life.",否则,输出最短的时间。

  对就类似于迷宫类题目,直接使用bfs搜索,但是由于需要最短的时间,所以需要使用优先队列保存节点。直接使用stl库里面的priority_queue,当然,也可以自己写一个优先队列。

#include <iostream>
#include <cstdio>
#include <cstring>
#include <queue>
using namespace std;
const int maxn=205;
const int INF=1<<30;
int ans;
int n,m;
struct node
{
    int r,c;
    int t;
    bool operator < (const node &a)const
    {
        return a.t<t;
    }
};
char mp[maxn][maxn];
bool vis[maxn][maxn];
int dr[4][2]={{0,1},{1,0},{0,-1},{-1,0}};
bool bfs(int x,int y)
{

    priority_queue<node> que;
    node now;
    now.r=x;
    now.c=y;
    now.t=0;
    vis[x][y]=true;
    que.push(now);
    while(!que.empty())
    {
        now=que.top();
        que.pop();
        for(int i=0;i<4;i++)
        {
            node tmp;
            tmp.r=now.r+dr[i][0];
            tmp.c=now.c+dr[i][1];
            tmp.t=now.t;
            if(tmp.r>0 && tmp.r<=n && tmp.c>0 && tmp.c<=m)
            {
                if(vis[tmp.r][tmp.c])continue;
                if(mp[tmp.r][tmp.c]=='r')
                {
                    ans=tmp.t+1;
                    return true;
                }
                if(mp[tmp.r][tmp.c]=='.')
                {
                    tmp.t++;
                    que.push(tmp);
                    vis[tmp.r][tmp.c]=true;
                }
                if(mp[tmp.r][tmp.c]=='x')
                {
                    tmp.t+=2;
                    que.push(tmp);
                    vis[tmp.r][tmp.c]=true;
                }

            }
        }
    }
    return false;
}
void init()
{
    ans=INF;
    memset(vis,false,sizeof(vis));
}
void solve(int x,int y)
{
    init();
    if(bfs(x,y))
    {
        printf("%d\n",ans);
    }
    else printf("Poor ANGEL has to stay in the prison all his life.\n");
}
int main()
{
    int x,y;
  //  freopen("in.txt","r",stdin);
    while(~scanf("%d%d",&n,&m))
    {
        for(int i=1;i<=n;i++)
          scanf("%s",mp[i]+1);
        bool isf=false;
        for(int i=1;i<=n && !isf;i++)
            for(int j=1;j<=m;j++)
              if(mp[i][j]=='a')
              {
                  x=i;
                  y=j;
                  isf=true;
                  break;
              }
        solve(x,y);
    }
    return 0;
}


 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值