HDU 1026 (BFS+优先队列)


BFS+优先队列,做这个题的时候只要保存路径的前驱就行啦!!其他没有处理。

虽然一次性AC,但是打了好久,手都累了。(还加上改错吧!!)

AC代码:

#include<iostream>
#include<cstring>
#include<cstdio>
#include<queue>
using namespace std;
char q[108][108];
int w[108][108];
int m,n;
struct node1{  //保存前驱节点。。
	int pre_x,pre_y;
}r[108][108];

struct node{//优先队列
	int a,b;
	int pri;
	bool operator<(const node &t)const{
		return pri>t.pri;
	}
};
int getes(int a,int b){  //判断是否满足条件。。
	if(a>=1 && a<=n && b >=1 && b <=m && q[a][b] != 'X' && w[a][b]==0){
		return 1;
	}
	return 0;
}
int dir[4][2]={{1,0},{-1,0},{0,1},{0,-1}};
int bfs(int x,int y){
	priority_queue<node> que;
	node in,out;
	int c,d,i;
	in.a=in.b=1;
	in.pri=0;
	r[1][1].pre_x=r[1][1].pre_y=0;
	que.push(in);
	while(que.size() != 0){
		out=que.top();
		que.pop();
		c=out.a;
		d=out.b;
		//printf(" %d %d %d\n",c,d,out.pri);
		if(c == n && d == m){
			return out.pri;
		}
		for(i=0;i<4;i++){
			c=out.a+dir[i][0];
			d=out.b+dir[i][1];
			//printf("  %d  %d\n",c,d);
			if(getes(c,d) == 1){
				w[c][d]=1;
				in.a=c;
				in.b=d;
				in.pri=out.pri+1;
				r[c][d].pre_x=out.a;
				r[c][d].pre_y=out.b;
				if(q[c][d]<='9' && q[c][d] >= '1'){
					in.pri+=(q[c][d]-'0');
				}
				que.push(in);
			}
		}
	}
	return 0;
}

void outxp(int x,int y,int z){ //输出函数
	int e,f,ant,i;
	if(x==1 && y == 1){
		return ;
	}
	e=r[x][y].pre_x;
	f=r[x][y].pre_y;
	z=z-1;
	if(q[x][y]<='9' && q[x][y] >= '1'){
		ant=(q[x][y]-'0');
		z=z-ant;
	}	
	outxp(e,f,z);
	printf("%ds:(%d,%d)->(%d,%d)\n",z,e-1,f-1,x-1,y-1);
	if(q[x][y]<='9' && q[x][y] >= '1'){
		ant=(q[x][y]-'0');
		for(i=1;i<=ant;i++){
			printf("%ds:FIGHT AT (%d,%d)\n",z+i,x-1,y-1);
		}
	}	
}
int main(){
	int i,j,sum;
	while(~scanf("%d%d",&n,&m)){
		for(i=1;i<=n;i++){
			for(j=1;j<=m;j++){
				cin>>q[i][j];
			}
		}
		memset(w,0,sizeof(w));
		memset(r,0,sizeof(r));
		w[1][1]=1;
		sum=bfs(1,1);
		if(sum == 0){
			printf("God please help our poor hero.\n");
		}
		else{
			printf("It takes %d seconds to reach the target position, let me show you the way.\n",sum);
			outxp(n,m,sum+1);  //输出函数。。
		}
		printf("FINISH\n");
	}
	return 0;
}

路途中。。。。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值