12rescue

简单题意

给出一定区域,a代表天使,r代表朋友,#代表墙,.代表路,x代表守卫,只能上下左右四个方向,求出朋友找到天使的最短时间(走一步耗时1,若杀死守卫耗时再加1)

解题思路形成过程

简单的广搜输入数据的时候记录起始和终止的位置,从起始开始四个方向广搜,注意遇到守卫总耗时要加2,直到找到天使为止

感想

渐渐明白了广搜的模式套路。

AC代码

#include <fstream>
#include<iostream>
#include<queue>
#include<cstdio>
using namespace std;
class data
{
public:
    int x,y,cost;
    friend bool operator<(data a,data b)
    {
        return b.cost<a.cost;
    }
};
int N,M;
char map[205][205];
int sx,sy,ex,ey;
int xy[4][2]={1,0,-1,0,0,1,0,-1};
int bfs()
{
    priority_queue<data>que;
    data temp;
    temp.x=sx;temp.y=sy;temp.cost=0;
    que.push(temp);
    map[sx][sy]='#';
    while(!que.empty())
    {
        temp=que.top();
        que.pop();
        if(temp.x==ex&&temp.y==ey)
            return temp.cost;
        int fx,fy;
        for(int i=0;i<4;i++)
        {
            fx=temp.x+xy[i][0];
            fy=temp.y+xy[i][1];
            if(fx>=0&&fx<N&&fy>=0&&fy<M&&map[fx][fy]!='#')
            {
                data te;
                if(map[fx][fy]=='.'||map[fx][fy]=='a'){
                    te.x=fx;te.y=fy;te.cost=temp.cost+1;
                }else{
                    te.x=fx;te.y=fy;te.cost=temp.cost+2;
                }
                que.push(te);
                map[fx][fy] = '#';
            }
        }
    }
    return -1;
}

int main()
{
    ifstream cin("in.txt");
    while(cin>>N>>M)
    {
        for(int i=0;i<N;i++)
        {
            for(int j=0;j<M;j++)
            {
            cin>>map[i][j];
                if(map[i][j]=='r')
                {
                    sx=i;
                    sy=j;
                }
                if(map[i][j]=='a')
                {
                    ex=i;
                    ey=j;
                }
            }
        }
        int ans=bfs();
        if(ans==-1)
            printf("Poor ANGEL has to stay in the prison all his life.\n");
        else
            printf("%d\n",ans);
    }
    return 0;
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值