HDU1026 Ignatius and the Princess I(BFS+优先队列)

题目链接

题意:

输入N*M大小的迷宫,’.'表示可以走,'X’表示不可以走,'n’表示扩展此结点需要n步,求解(0,0)到(N-1,M-1)的最短距离并输出路径

思路:

迷宫问题的变式,扩展“怪物”结点的用时要加上怪物的HP,故可采用优先队列,优先扩展用时最少的结点。为了便于输出路径,先将终点入队,寻找终点到起点的路径,并把路径记录在一个pair类型的二维数组里(存储被扩展结点的父节点的坐标),这样BFS结束后就可以直接顺序输出路径了。

代码实现

#include <iostream>
#include <queue>
#include <vector>
#include <cstring>
using namespace std;

int m,n;
char maze[110][110];
bool vis[110][110];
pair<int,int> path[110][110];
int dis[][2]={{-1,0},{1,0},{0,-1},{0,1}};

struct s{
	int x;
	int y;
	int t;
	s(){}
	s(int xx,int yy,int tt):x(xx),y(yy),t(tt){}
	friend bool operator <(const s &s1,const s &s2){
		return s1.t>s2.t;
	}
};

int main()
{
	ios::sync_with_stdio(false);
	cin.tie(0);
	cout.tie(0);
	while(cin>>n>>m){
		memset(vis,0,sizeof(vis));
		memset(path,0,sizeof(path));
		priority_queue<s> q;
		for(int i=0;i<n;i++){
			for(int j=0;j<m;j++){
				cin>>maze[i][j];
				if(maze[i][j]=='X')
					vis[i][j]=1;
			}
		}
		q.push(s(n-1,m-1,0));
		vis[n-1][m-1]=1;
		bool flag=false;
		while(!q.empty()){
			s t=q.top();
			if(t.x==0&&t.y==0){
				flag=true;
				break;
			}
			for(int i=0;i<4;i++){
				int dx=t.x+dis[i][0];
				int dy=t.y+dis[i][1];
				int dt=t.t+1;
				if(dx>=0&&dy>=0&&dx<n&&dy<m&&!vis[dx][dy]){
					vis[dx][dy]=1;
					if(maze[dx][dy]=='.'){
						q.push(s(dx,dy,dt));	
					}
					else{
						int hp=maze[dx][dy]-'0';
						q.push(s(dx,dy,dt+hp));
					}
					path[dx][dy]={t.x,t.y};
				}
			}
			q.pop();
		}
		if(flag){
			int mint=q.top().t;
			if(maze[n-1][m-1]>='0'&&maze[n-1][m-1]<='9')
				mint+=maze[n-1][m-1]-'0';
			cout<<"It takes "<<mint<<" seconds to reach the target position, let me show you the way."<<endl;
			int a,b,c,d,t;
			a=b=0;t=1;
			while(t<=mint){
				c=path[a][b].first;d=path[a][b].second;
				if(maze[a][b]=='.')
					cout<<t++<<"s:("<<a<<","<<b<<")->("<<c<<","<<d<<")"<<endl;
				else{
					int count=maze[a][b]-'0';
					while(count--)
						cout<<t++<<"s:FIGHT AT ("<<a<<","<<b<<")"<<endl;
					if(t<mint)
						cout<<t++<<"s:("<<a<<","<<b<<")->("<<c<<","<<d<<")"<<endl;
				}
				a=c,b=d;
			}
		}
		else{
			cout<<"God please help our poor hero."<<endl;
		}
		cout<<"FINISH"<<endl;
	}
	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值