HDU1242 Rescue (BFS)

                                            Rescue题目链接

题意:'a'为终点,'x'为守卫,经过需要2s时间,'.'为道路,经过需要1s时间,'#'为障碍,无法经过,'r'为起始点,求起点至终点的最短时间,无法到达则输出'Poor ANGEL has to stay in the prison all his life."

HDU1242 Rescue (BFS)_第1张图片

思路:BFS + 优先队列(花费时间长的优先级小)

AC Code:

#include 
#include 
#include 
#include 
#include 
#include 
#include 
using namespace std;
static const int dir[4][2] = { {1, 0}, {-1, 0}, {0, -1}, {0, 1} };	//定义上下左右四个方向
int n, m;
char maps[205][205];	//迷宫地图
bool vis[205][205];	//标记是否访问过某点
int sx, sy, ex, ey;
struct Point {
	int x;
	int y;
	int step;
	bool operator < (const Point &p) const {	//自定义优先级
		return step > p.step;	//步数小的优先级大
	}
};

bool inbound(int x, int y) {	//边界判断
	return (x >= 0 && x < n && y >= 0 && y < m);
}

void bfs() {
	memset(vis, false, sizeof(vis));
	priority_queue >pq;	//用于优先队列
	Point p1, p2;
	vis[sx][sy] = true;
	p1.x = sx;
	p1.y = sy;
	p1.step = 0;
	pq.push(p1);
	while (!pq.empty()) {
		p1 = pq.top();
		if (p1.x == ex && p1.y == ey) {	//到达终点
			printf("%d\n", p1.step);
			return;
		}
		pq.pop();
		for (int k = 0; k < 4; k++) {
			p2.x = p1.x + dir[k][0];
			p2.y = p1.y + dir[k][1];
			p2.step = p1.step + 1;
			if (inbound(p2.x, p2.y) && !vis[p2.x][p2.y] && maps[p2.x][p2.y] != '#') {
				if (maps[p2.x][p2.y] == 'x') {	//'x'点需要两步
					p2.step++;
				}
				vis[p2.x][p2.y] = true;
				pq.push(p2);
			}
		}
	}
	printf("Poor ANGEL has to stay in the prison all his life.\n");
}
int main() {
	while (scanf("%d%d", &n, &m) != EOF) {
		for (int i = 0; i < n; i++) {
			scanf("%s", maps[i]);
			for (int j = 0; j < m; j++) {
				if (maps[i][j] == 'r') {
					sx = i;
					sy = j;
				}
				if (maps[i][j] == 'a') {
					ex = i;
					ey = j;
				}
			}
		}
		bfs();
	}
}

 

你可能感兴趣的:(HDU1242 Rescue (BFS))