HDU 1026 Ignatius and the Princess I (bfs + 优先队列 + 路径记录)

HDU 1026


通过记录前驱来记录路径,不用担心所记录的路径不是用时最少的路径,因为优先队列每次出队的都是用时最少的元素,所以当不合适的元素出队时,正确的路径早已被标记完了。 另外,(0, 0)点确实是没有怪兽的。


#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <queue>
using namespace std;
char map[110][110];
int vis[110][110];
int dir[4][2] = {1, 0, 0, 1, -1, 0, 0, -1};
int N, M;
struct node {
	int x, y;
	int time;
	friend bool operator < (node a, node b) {
		return a.time > b.time;
	}
};
int pre[110][110];
int t;
int bfs() {
	int i, j;
	priority_queue<node> q;
	node now, next;
	now.x = 0, now.y = 0, now.time = 0;
	q.push(now);
	while(!q.empty()) {
		now = q.top();
		q.pop();
		if(now.x == N - 1 && now.y == M - 1) {
			return now.time;
		}
		vis[now.x][now.y] = 1;
		for(i = 0; i < 4; i++) {
			next.x = now.x + dir[i][0];
			next.y = now.y + dir[i][1];
			if(next.x >= 0 && next.x <= N - 1 && next.y >= 0 && next.y <= M - 1) {
				if(vis[next.x][next.y] == 0 && map[next.x][next.y] != 'X') {
					if(map[next.x][next.y] == '.') {
						next.time = now.time + 1;
					}
					else if(map[next.x][next.y] >= '1' && map[next.x][next.y] <= '9') {
						next.time = now.time + map[next.x][next.y] - '0' + 1;
					}
					vis[next.x][next.y] = 1;
					pre[next.x][next.y] = i;
					q.push(next);
				}
			}
		}
	}
	return -1;
}
void path(int x, int y) {
	if(x == 0 && y == 0) {
		return;
	}
	int tx = x - dir[pre[x][y]][0];
	int ty = y - dir[pre[x][y]][1];
	path(tx, ty);
	printf("%ds:(%d,%d)->(%d,%d)\n", t++, tx, ty, x, y);
	if(map[x][y] >= '1' && map[x][y] <= '9') {
		int i;
		for(i = 1; i <= map[x][y] - '0'; i++) {
			printf("%ds:FIGHT AT (%d,%d)\n", t++, x, y);
		}
	}
}
int main() {
	while(~scanf("%d %d", &N, &M)) {
		getchar();
		int i, j;
		for(i = 0; i < N; i++) {
			for(j = 0; j < M; j++) {
				scanf("%c", &map[i][j]);
			}
			getchar();
		}
		memset(vis, 0, sizeof(vis));
		memset(pre, 0, sizeof(pre));
		int step = bfs();
		if(step != -1) {
			printf("It takes %d seconds to reach the target position, let me show you the way.\n", step);
			t = 1;
			path(N - 1, M - 1);
		}
		else {
			printf("God please help our poor hero.\n");
		}
		printf("FINISH\n");
	}
    return 0;
}


你可能感兴趣的:(HDU 1026 Ignatius and the Princess I (bfs + 优先队列 + 路径记录))