Rescue(BFS + 优先队列)|HDU1242

Rescue

Rescue

  • 'x’的权值是2,其他的权值是1
  • 用优先队列对插入的节点排序,时间消耗小的排在队首
  • 每次都从时间消耗小的开始向四周发散(BFS)
#include <iostream>
#include<queue>
using namespace std;

struct Node {
	int x, y, step;
	Node(int a = 0, int b = 0, int c = 0) {
		x = a, y = b, step = c;
	}
	friend bool operator<(Node a, Node b) {// 时间消耗大的权值小
		return a.step > b.step;
	}
};

int n, m, sx, sy, gx, gy;
char maze[205][205];
int vis[205][205];
int dx[] = { 1,0,0,-1 };
int dy[] = { 0,1,-1,0 };

void bfs() {
	int ans = 0;
	int flag = 0;
	memset(vis, -1, sizeof(vis));
	priority_queue<Node> que;// 优先级高的在队首
	que.push(Node(sx, sy, 0));
	vis[sx][sy] = 1;
	while (!que.empty()) {
		Node u = que.top();
		que.pop();
		int x = u.x, y = u.y;
		if (x == gx && y == gy) {
			ans = u.step;
			flag = 1;
			break;
		}
		for (int i = 0; i < 4; i++) {
			int nx = x + dx[i], ny = y + dy[i];
			if ((0 <= nx && x < n) && (0 <= ny && ny < m) && (maze[nx][ny] != '#') && (vis[nx][ny] == -1)) {
				int step;
				if (maze[nx][ny] == 'x') step = u.step + 2;
				else step = u.step + 1;
				que.push(Node(nx, ny, step));
				vis[nx][ny] = 1;
			}
		}
	}
	if (flag) cout << ans << endl;
	else cout << "Poor ANGEL has to stay in the prison all his life." << endl;
}

int main()
{
	while (cin >> n >> m) {
		for (int i = 0; i < n; i++)
			for (int j = 0; j < m; j++) {
				cin >> maze[i][j];
				if (maze[i][j] == 'a') sx = i, sy = j;
				if (maze[i][j] == 'r') gx = i, gy = j;
			}
		bfs();
	}
	return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值