HDOJ 1242 BFS+priority_queue

7 篇文章 0 订阅
2 篇文章 0 订阅

题目:http://acm.hdu.edu.cn/showproblem.php?pid=1242

#include<bits/stdc++.h>
#define PI 3.1415926 
#define INF 1e18 
#define inf 1e9
#define min(a,b) a<b?a:b
#define max(a,b) a>b?a:b
using namespace std ;
typedef long long ll;
typedef unsigned long long ull;

const int _max = 205;
struct node{
    int x,y,cnt;
    void init(int x,int y,int cnt){
        this->x=x;
        this->y=y;
        this->cnt=cnt;
    }
    bool operator < (const node &n1)const{
        return cnt > n1.cnt;
    }
};
char mp[_max][_max];
bool vis[_max][_max];
int dx[]={0,0,1,-1};
int dy[]={1,-1,0,0};
int n,m;
bool outside(node n1){
    if(n1.x < 1 || n1.x > m) return true;
    if(n1.y < 1 || n1.y > n) return true;
    return false;
}
int dfs(int sx,int sy,int ex,int ey){
    node now,next;
    priority_queue<node> q;
    while(!q.empty()) q.pop();
    now.init(sx,sy,0);
    q.push(now);
    vis[sy][sx]=false;
    while(!q.empty()){
        now = q.top();
        q.pop();
        if(now.x == ex && now.y == ey)
            return now.cnt;
        for(int i = 0 ; i < 4 ; i++){
            next.init(now.x+dx[i],now.y+dy[i],now.cnt+1);
            if(!outside(next)&&vis[next.y][next.x]&&mp[next.y][next.x]!='#'){
                if(mp[next.y][next.x]=='x')
                    next.cnt++;
                vis[next.y][next.x] = false;
                q.push(next);
            }
        }
    }
    return -1;  
}
int main(){
    int sx,sy,ex,ey;
    while(cin>>n>>m){
        memset(vis,true,sizeof(vis));
        for(int y = 1 ; y <= n ; y++)
            for(int x = 1 ;  x <= m ; x++){
                cin >> mp[y][x];
                if(mp[y][x]=='r'){
                    sx = x;
                    sy = y;
                }
                if(mp[y][x]=='a'){
                    ex = x;
                    ey = y;
                }
            }   
        int ans =dfs(sx,sy,ex,ey);
        if(ans == -1) cout<<"Poor ANGEL has to stay in the prison all his life."<<endl;
        else cout<<ans<<endl;
    }
    return 0 ;
}

终于摆脱了,见到迷宫就dfs的场景了。

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值