HDU 1242 Rescue (BFS+优先队列)

17 篇文章 1 订阅

从天使的位置开始,直到找到r,优先队列每次选择最短时间的路

#include<iostream>
#include<algorithm>
#include<cstring>
#include<string>
#include<sstream>
#include<queue>
using namespace std;
typedef long long LL;
const int INF = 0x3f3f3f3f;
const int M = 1010;

struct node
{
	int x, y, step;
	bool operator <(const node &b)const
	{
		return step > b.step;
	}
};

int n, m;
priority_queue<node>q;
char mp[210][210];
int sx, sy;
bool vis[210][210];
int dir[][2] = { 1,0,-1,0,0,1,0,-1 };


int bfs()
{
	node st;
	st.x = sx;
	st.y = sy;
	st.step = 0;
	vis[sx][sy] = 1;
	q.push(st);
	while (!q.empty())
	{
		node nw = q.top();
		q.pop();
		if (mp[nw.x][nw.y] == 'r')
		{
			return nw.step;
		}
		for (int i = 0; i < 4; ++i)
		{
			int xx = nw.x + dir[i][0];
			int yy = nw.y + dir[i][1];
			if(xx<0 ||xx>=n ||yy<0||yy>=m ||vis[xx][yy])
				continue;
			if(mp[xx][yy]=='#')
				continue;
			if (mp[xx][yy] == 'x')
			{
				vis[xx][yy] = 1;
				node nx;
				nx.x = xx;
				nx.y = yy;
				nx.step = nw.step + 2;
				q.push(nx);
			}
			else
			{
				vis[xx][yy] = 1;
				node nx;
				nx.x = xx;
				nx.y = yy;
				nx.step = nw.step + 1;
				q.push(nx);
			}

		}

	}
	return -1;
}


int main()
{
	while (~scanf("%d%d", &n, &m))
	{
		for (int i = 0; i < n; ++i)
		{
			for (int j = 0; j < m; ++j)
			{
				cin >> mp[i][j];
				if (mp[i][j] == 'a')
				{
					sx = i;
					sy = j;
				}

			}
		}
		memset(vis, 0, sizeof(vis));
		int flag=bfs();
		if (flag == -1)
		{
			puts("Poor ANGEL has to stay in the prison all his life.");
		}
		else
		{
			printf("%d\n", flag);
		}
	}

	return 0;
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值