HDU 1242 Rescue【优先队列BFS】

题目很短,好理解。存在多个目标r。单纯的普通队列+BFS是错的,即使你A了,换个遍历方向就WA了,见图


自己敲的代码比别人的好看多了

#include<cstdio>
#include<cmath>
#include<cstring>
#include<queue>
#include<stack>
#include<iostream>
#include<algorithm>
using namespace std;
#define ll long long
#define INF 0x7F7F7F7F
#define eps 10^(-6)
#define MEM(a) memset(a,0,sizeof(a));
#define MEM_BOOL(a) memset(a,false,sizeof(a));
#define FOR(i,n) for(int i=0;i<n;i++)
#define FIN freopen("in.txt","r",stdin);
#define FOUT freopen("out.txt","w",stdout);
#define NMAX 202
int dir[4][2]={{-1,0},{0,1},{1,0},{0,-1}};
int n,m;
char map[NMAX][NMAX];
bool visit[NMAX][NMAX];
struct node
{
    int x,y;
    int step;
    bool operator < (const node &A)const
    {
        return step > A.step;   //最小时间
    }
};

bool isok(int x,int y)
{
    if(map[x][y] != '#')
        if(x >= 0 && x < n)
            if(y >= 0 && y < m)
                return 1;
    return 0;
}
int bfs(node s)
{
    node cur,tmp;
    priority_queue<node>q;
    while(!q.empty())
        q.pop();
    visit[s.x][s.y] = true;
    q.push(s);
    while(!q.empty())
    {
        tmp = q.top();
        q.pop();
        for(int i=0;i<4;i++)
        {
            cur.x = tmp.x + dir[i][0];
            cur.y = tmp.y + dir[i][1];
            if(!visit[cur.x][cur.y] && isok(cur.x,cur.y))
            {
                cur.step = tmp.step + 1;
                if(map[cur.x][cur.y] == 'x')
                   cur.step ++;
                if(map[cur.x][cur.y] == 'r')
                    return cur.step;
                visit[cur.x][cur.y] = true;
                q.push(cur);
            }
        }
    }
    return -1;
}
int main()
{
    node s;
    //FIN
    int ans;
	while(scanf("%d%d%*c",&n,&m)!=EOF)
    {
        MEM_BOOL(visit);
        FOR(i,n)
        {
            FOR(j,m)
            {
                scanf("%c",&map[i][j]);
                if(map[i][j] == 'a')
                    s.x = i, s.y = j,s.step = 0;
            }
            getchar();
        }
        ans = bfs(s);
        if(ans != -1)
            cout<<ans<<endl;
        else
            cout<<"Poor ANGEL has to stay in the prison all his life."<<endl;
    }
	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值