hdu 1242 优先队列BFS,DFS

传送门
常见的迷宫最短路,不同的是路上还有妖怪,每干掉一个妖怪要1单元的时间,于是先放进队列里的时间消耗不一定更小,所以可以使用优先队列下的BFS,来求最短路。
时间复杂度:O(n*m*(log(n*m))

#include <bits/stdc++.h>

using namespace std;

#define ll long long
#define N 205
#define mod 1000000007
#define INF 0x3f3f3f3f

const double eps=1e-8;
const double pi=acos(-1.0);

struct node{
    int x, y;
    int cost;
    node(int _x, int _y):x(_x), y(_y), cost(0){};
    friend bool operator < (const node a, const node b){
        return a.cost > b.cost; // 小顶堆
        // a.cost < b.cost 大顶堆,优先队列默认权值大优先级大,所以默认是大顶堆
    }
};

int go[4][2]={{1,0},{-1,0},{0,1},{0,-1}};

int vis[N][N];
char mp[N][N];
int n,m;
int sx,sy,ex,ey;

int BFS(int sx, int sy)
{
    memset(vis, 0, sizeof(vis));

    priority_queue<node> q;
    q.push(node(sx, sy));

    while(!q.empty()){
        node cur=q.top(); q.pop();
        for(int i=0;i<4;i++){
            int x=cur.x+go[i][0];
            int y=cur.y+go[i][1];
            if(x>=0&&x<n && y>=0&&y<m && !vis[x][y] && mp[x][y]!='#'){
                vis[x][y]=1;

                node next(x, y);
                next.cost=cur.cost+1;
                if(mp[x][y]=='x') next.cost++;

                if(next.x==ex && next.y==ey)
                    return next.cost;

                q.push(next);
            }
        }
    }
    return -1;
}


int main()
{
    while(cin>>n>>m){
        for(int i=0;i<n;i++) cin>>mp[i];

        for(int i=0;i<n;i++){
            for(int j=0;j<m;j++){
                if(mp[i][j]=='r') sx=i, sy=j;
                else if(mp[i][j]=='a') ex=i, ey=j;
            }
        }

        int ans=BFS(sx, sy);

        if(ans!=-1) cout<<ans<<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、付费专栏及课程。

余额充值