HDU 1026 Ignatius and the Princess I (BFS+记录路径)

本文介绍了解决HDU1026问题的一种方法,该问题要求找到从左上角到右下角的最短路径,并处理路径上的怪物攻击。通过使用BFS(宽度优先搜索)算法,文章详细解释了如何实现这一过程并提供了一个完整的C++代码示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

HDU 1026 Ignatius and the Princess I 

题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1026

题意:就是从左上角到又下角的最短距离,过程中有数字代表怪兽的HP。打一滴血要花费一步时间。

直接BFS就好了


AC代码:


#include<stdio.h>
#include<queue>
#include<string.h>
using namespace std;

struct node
{
	int x,y,step;
	int f;
	bool operator <(const node &a) const
    {
        return step>a.step;
    }
};
struct node front,next,res[110][110];

int n,m,cnt,k1,k2,rx,ry,ss;
int xx[4]={0,0,-1,1};
int yy[4]={-1,1,0,0};
char map[110][110];
bool vis[110][110];
int mark[110][110];

priority_queue<node>q;

int BFS(int x,int y,int ansx,int ansy)
{
	int i,dx,dy,k=-1;
	memset(vis,false,sizeof vis);
	if(x==ansx && y==ansy)
		return 0;
	front.x=x;
	front.y=y;
	front.step=0;
	vis[x][y]=true;
	q.push(front);
	while(!q.empty())
	{
		front=q.top();
		q.pop();
		for(i=0;i<4;i++)		
		{
			dx=front.x+xx[i];
			dy=front.y+yy[i];
			
			if(dx>=0 && dx<n && dy>=0 && dy<m && map[dx][dy]!='X' && !vis[dx][dy])
			{
				vis[dx][dy]=true;
				next.x=dx;
				next.y=dy;
				next.step=front.step+mark[dx][dy]+1;
				
				res[dx][dy].step=k;
				res[dx][dy].f=mark[front.x][front.y];
				res[dx][dy].x=front.x;
				res[dx][dy].y=front.y;
				
				if(dx==ansx && dy==ansy)
					return next.step;
				q.push(next);
			}
		}
		k++;
	}
	return -1;
}

void print(int x,int y)
{
	int i;
	if(res[x][y].step!=(-1))
		print(res[x][y].x,res[x][y].y);
	if(res[x][y].f<1)
	{
		printf("%ds:",ss++);
		printf("(%d,%d)->(%d,%d)\n",res[x][y].x,res[x][y].y,x,y);
	}
	else
	{
		for(i=0;i<res[x][y].f;i++)
		{
			printf("%ds:",ss++);
			printf("FIGHT AT (%d,%d)\n",res[x][y].x,res[x][y].y);
		}
		printf("%ds:",ss++);
		printf("(%d,%d)->(%d,%d)\n",res[x][y].x,res[x][y].y,x,y);
	}
}

int main()
{
	int i,j;
	while(scanf("%d %d",&n,&m)!=EOF)
	{
		while(!q.empty())
			q.pop();
		memset(mark,0,sizeof mark);
		memset(map,0,sizeof map);
		memset(res,0,sizeof res);
		for(i=0;i<n;i++)
			scanf("%s",map[i]);
		for(i=0;i<n;i++)
		{
			for(j=0;j<m;j++)
			{
				if(map[i][j]>='0' && map[i][j]<='9')
					mark[i][j]=map[i][j]-'0';
			}
		}
		cnt=0;
		k1=0,k2=-1;
		rx=0,ry=0;
		int ans=BFS(rx,ry,n-1,m-1);
		if(ans==-1)
			printf("God please help our poor hero.\n");
		else
		{
			ss=1;
			printf("It takes %d seconds to reach the target position, let me show you the way.\n",ans);
			print(n-1,m-1);
			if(mark[n-1][m-1]>0)
			{
				for(i=0;i<mark[n-1][m-1];i++)
				{
					printf("%ds:",ss++);
					printf("FIGHT AT (%d,%d)\n",n-1,m-1);
				}
			}
		}
		puts("FINISH");
	}
	return 0;
}

/*
3 3
...
.1X
.2.


5 6
......
......
......
.....X
....2.
	
*/


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值