hdu1026 Ignatius and the Princess I

http://acm.hdu.edu.cn/showproblem.php?pid=1026

题目大意:

就是搜索算法加上保存路径。

用一个数组来保存每一次移动时的方向,最后再从终点向起点递归输出。

#include<iostream>
#include<stdio.h>
#include<string.h>
#include<queue>
using namespace std;
int n,m;
int a[4][2]={{1,0},{-1,0},{0,-1},{0,1}};
struct node
{
	int x,y;
	int step;
	friend bool operator<(node x,node y)
	{
		return x.step>y.step;
	}
	
};
int map[105][105];
int blood[105][105];
int flag[105][105];
int bfs()
{
	int i,j,xx,yy;
	node cur,next;
	priority_queue<node>q;
	cur.x=0;
	cur.y=0;
	cur.step=0;
	q.push(cur);
	while(!q.empty())
	{
		cur=q.top();
		q.pop();
		if(cur.x==n-1&&cur.y==m-1)
		return cur.step;
		for(i=0;i<4;i++)
		{
			next=cur;
			next.x=cur.x+a[i][0];
			next.y=cur.y+a[i][1];
			if(next.x>=0&&next.x<n&&next.y>=0&&next.y<m&&map[next.x][next.y]>0)
			{
				next.step=cur.step+map[next.x][next.y];
				map[next.x][next.y]=-1;
				flag[next.x][next.y]=i;
			//	printf("i=%d %d %d %d %d\n",i,cur.x,cur.y,next.x,next.y);
				q.push(next);
			
			}
		}
	}
	return -1;
	
}
int tmp;
void p(int x,int y)
{
	int xx,yy;
	if(flag[x][y]==-1)
	return;
	xx=x-a[flag[x][y]][0];
	yy=y-a[flag[x][y]][1];
//	printf("%d %d\n",xx,yy);
	p(xx,yy);
	printf("%ds:(%d,%d)->(%d,%d)\n",tmp++,xx,yy,x,y);
	while(blood[x][y]--)
	printf("%ds:FIGHT AT (%d,%d)\n",tmp++,x,y);
}
int main()
{
	char st[105];
	while(scanf("%d%d",&n,&m)!=EOF)
	{
	
		int i,j;
		int ans;
		memset(flag,-1,sizeof(flag));
		memset(map,-1,sizeof(map));
		memset(blood,0,sizeof(blood));
		for(i=0;i<n;i++)
		{
			scanf("%s",st);
			for(j=0;j<m;j++)
			{
				if(st[j]=='X')
				map[i][j]=-1;
				else if(st[j]=='.')
				map[i][j]=1;
				else
				{
					map[i][j]=st[j]-'0'+1;
					blood[i][j]=st[j]-'0';
				}
			//printf("%d",map[i][j]);
			}
		//	printf("\n");
		}	
		map[0][0]=-1;
		ans=bfs();
		if(ans==-1)
		{
			printf("God please help our poor hero.\n");
		}
		else
		{	tmp=1;
		//printf("%d\n",flag[n-1][m-1]);
		//printf("0 0 %d\n",flag[0][0]);
		printf("It takes %d seconds to reach the target position, let me show you the way.\n",ans);
		p(n-1,m-1);
		
		}	
		printf("FINISH\n");
	}
}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值