HDU 1242 Rescue (BFS + 优先队列)

#include<cstdio>
#include<queue>
#include<cstring>
using namespace std;
const int maxn=200+10;
char p[maxn][maxn];        //保存字符
int d[maxn][maxn];          //从开始位置到当前位置花的时间长度
struct node{
	int x,y;
	node(int x1=0,int y1=0):x(x1),y(y1){}
	bool operator<(const node & n)const{
	return d[x][y]>d[n.x][n.y];
	}
};
node a;
node r;
int N,M;
const int dir[][2]={{-1,0},{1,0},{0,-1},{0,1}};
bool isValid(const node &v){                  
	return v.x>=0 && v.x<N && v.y>=0 && v.y<M;
}
void bfs(){
	priority_queue<node>q;          //优先队列,整数值越小越先出队列
    q.push(r);
    memset(d,0,sizeof(d));
    while(!q.empty()){
    	node u=q.top();q.pop();
    	if(u.x== a.x && u.y== a.y){           //如果找到 Angel 就 输出所花时间 并退出 BFS
         printf("%d\n",d[u.x][u.y]);    
		 return ;	    
		}
		for(int i=0;i<4;i++){
			node v=node(u.x+dir[i][0],u.y+dir[i][1]);
			if(isValid(v)&& !d[v.x][v.y] && p[v.x][v.y]!='#'){
				if(p[v.x][v.y]=='x')d[v.x][v.y]=d[u.x][u.y]+2;
				else d[v.x][v.y]=d[u.x][u.y]+1;
			     q.push(v);
			}
		}
	}
printf ("Poor ANGEL has to stay in the prison all his life.\n");
}
int main(){
	while(scanf("%d%d",&N,&M)==2){
		memset(p,0,sizeof(p));
		for(int i=0;i<N;i++)scanf("%s",p[i]);
		for(int i=0;i<N;i++){
			for(int j=0;j<M;j++){
				if(p[i][j]=='a'){
					a.x=i;a.y=j;
				}
				else if(p[i][j]=='r'){
					r.x=i;r.y=j;
				}
			}
		}
		bfs();
	}
	return 0;
}




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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

柏油

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值