HDU-1242:Rescue

/*代码非常的乱- -! 几经修改- -,终于AC了*/
/*逆序开始搜索,因为有可能有几个求援朋友,最先找到的则为最近的*/
#include<iostream>
#include<cstdio>
#include<cstring>
#include<queue>
using namespace std;
const int N=205;
char mp[N][N];
int vis[N][N];	//用于判断有没走过
int dir[4][2] = {{-1,0},{0,1},{1,0},{0,-1}};
int si,n,m,ei,ej,sj;
typedef struct Node	//使用优先队列。
{
	int x,y,step;
	bool operator <(const Node t)const
	{
		return step > t.step;
    }    
}Queue;

int main()
{
	int bfs();
	int i,j,step,flag;
	while(scanf("%d%d",&n,&m)!=EOF)
	{
		getchar();
		flag = -1;
		for(i=0;i<n;i++)
		{
			for(j=0;j<m;j++)
			{
				scanf("%c",&mp[i][j]);
				if (mp[i][j]=='r')	//即有朋友
					flag = 1;
				else if(mp[i][j]=='a')
					si=i,sj=j;
			}
			getchar();
		}
		if (flag==-1)	//表示如果没有求援朋友则直接输出
		{
			printf("Poor ANGEL has to stay in the prison all his life.\n");
			continue;
		}
		step = bfs();
		if (step!=-1)
			printf("%d\n",step);
		else printf("Poor ANGEL has to stay in the prison all his life.\n");
	}
	return 0;
}
int bfs()
{
	Queue tmp;
	Queue p;
	priority_queue<Queue>q;
	memset(vis,0,sizeof(vis));
	int i,j,di,xi,xj;

	tmp.x = si,	tmp.y = sj;	//初始化开始
	tmp.step = 0;
	vis[si][sj] = 1;
	q.push(tmp);

	while(!q.empty())
	{
		tmp = q.top();
		q.pop();
		i = tmp.x,	j = tmp.y;
		if (mp[i][j]=='r')	
			return tmp.step;
		for (di=0;di<4;di++)
		{
			xi = i + dir[di][0];
			xj = j + dir[di][1];
			if (xi>=0 &&xi<n &&xj>=0 &&xj<m && !vis[xi][xj]&&(mp[xi][xj]!='#'))
			{
				p.x = xi,	p.y = xj;
				if (mp[xi][xj]=='r')	
					return tmp.step+1;
				else if (mp[xi][xj]=='x')p.step = tmp.step+2;
				else p.step = tmp.step+1;
				q.push(p);
				vis[xi][xj] = 1;
			}
		}
	} 
	return -1;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值