hdu1026 BFS+路径保存

啊!!想抽自己!又是这种字符型迷宫的输入!!老是忘记getchar()会把空格回车都算进去!!!

新get路径保存的方法。。原来不用每个节点存路径。。。暴风哭泣

//递归打印路径。学习了
#include<iostream>
#include<queue>
#include<cstring>
#define maxn 102
using namespace std;
struct node{
	int x,y,sec;
	node(int xx,int yy,int ss):x(xx),y(yy),sec(ss){}
};
int dir[2][4] = {{1,0,-1,0},{0,1,0,-1}};
char map[maxn][maxn]; //地图 
int mark[maxn][maxn]; //标记走过的痕迹 
int n,m;
bool operator <(node a,node b){
	return a.sec>b.sec;
}
int bfs(){
	memset(mark,0,sizeof(mark));
	priority_queue<node> q;
	mark[0][0] = 1;  //方向随意
	q.push(node(0,0,0));
	while(!q.empty()){
		node a = q.top();q.pop();
		int x = a.x,y = a.y,sec = a.sec;
		if(x == n-1&& y == m-1){
			return sec;
		}
		for(int i = 0;i<4;i++){
			int xx = x+dir[0][i],yy = y+dir[1][i],ss = sec+1;
			if(xx>=0&&xx<n&&yy>=0&&yy<m&&!mark[xx][yy]&&map[xx][yy]!='X'){
				mark[xx][yy] = i+1; //标记方向
				if(map[xx][yy]!='.'){
					ss += map[xx][yy]-'0';
				}
				q.push(node(xx,yy,ss)); 	
			}
		}
	}
	return -1; 
}
//递归打印路径
void print_path(int x,int y,int sec){
	if(!(x+y)){
		return;
	}
	int dd = mark[x][y]-1;  //方向
	int xx = x-dir[0][dd];
	int yy = y-dir[1][dd];
	int time = (map[x][y]=='.'?0:map[x][y]-'0'); //当前位置打怪花费的时间 
	int ss = sec-1-time;
	print_path(xx,yy,ss);
	printf("%ds:(%d,%d)->(%d,%d)\n",sec-time,xx,yy,x,y);
	for(int i = time-1;i>=0;i--){
		printf("%ds:FIGHT AT (%d,%d)\n",sec-i,x,y);
	}
} 
int main(){
	char s[maxn];
	while(~scanf("%d%d",&n,&m)){
		for(int i = 0;i<n;i++){
			scanf("%s",&s);
			for(int j = 0;j<m;j++){
				map[i][j] = s[j];
			}
		}
		int ans = bfs();
		if(ans == -1){
			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",ans);
			print_path(n-1,m-1,ans);
		}
		printf("FINISH\n");
	
	}
	
	
	return 0;
} 


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值