Uva 11624 - Fire! (BFS)

题目链接 https://vjudge.net/problem/UVA-11624

【题意】

    大白书307页例题,走迷宫问题。

【思路】

    先用一个bfs求出大火蔓延到各个位置的最短时间,再用一个bfs求迷宫的最短路,当走到边缘时判断当前时间是否小于大火蔓延到该位置的时间即可,bfs的基础应用题。

#include<bits/stdc++.h>
using namespace std;

const int maxn = 1050;
const int dx[4] = { 0, 1, 0, -1 };
const int dy[4] = { 1, 0, -1, 0 };

int n, m;
char g[maxn][maxn];
int a[maxn][maxn];//火蔓延到i,j处的时间为a[i][j]
int b[maxn][maxn];//人跑到i,j处的时间为b[i][j]

struct node {
	int r, c;
	node(int rr = 0, int cc = 0) :r(rr), c(cc) {}
};

void bfs1() {
	queue<node> que;
	while (!que.empty()) que.pop();
	memset(a, -1, sizeof(a));//-1表示无法蔓延到

	for (int i = 0; i < n; ++i) {
		for (int j = 0; j < m; ++j) {
			if ('F' == g[i][j]) {
				a[i][j] = 0;
				que.push(node(i, j));
			}
		}
	}

	while (!que.empty()) {
		int r = que.front().r;
		int c = que.front().c;
		que.pop();
		
		for (int k = 0; k < 4; ++k) {
			int x = r + dx[k];
			int y = c + dy[k];

			if (x < 0 || x >= n || y < 0 || y >= m) continue;
			if ('#' == g[x][y]) continue;
			if (a[x][y] != -1) continue;

			a[x][y] = a[r][c] + 1;
			que.push(node(x, y));
		}
	}
}

int bfs2() {
	queue<node> que;
	while (!que.empty()) que.pop();
	memset(b, -1, sizeof(b));

	for (int i = 0; i < n; ++i) {
		for (int j = 0; j < m; ++j) {
			if ('J' == g[i][j]) {
				b[i][j] = 0;
				que.push(node(i, j));
				goto End;
			}
		}
	}
End:
	while (!que.empty()) {
		int r = que.front().r;
		int c = que.front().c;
		que.pop();
		if (r == 0 || r + 1 == n || c == 0 || c + 1 == m) {
			return b[r][c] + 1;
		}

		for (int k = 0; k < 4; ++k) {
			int x = r + dx[k];
			int y = c + dy[k];

			if (x < 0 || x >= n || y < 0 || y >= m) continue;
			if ('#' == g[x][y]) continue;
			if (-1 != b[x][y]) continue;
			if (-1 != a[x][y] && a[x][y] <= b[r][c] + 1) continue;

			b[x][y] = b[r][c] + 1;
			que.push(node(x, y));
		}
	}
	return -1;
}

int main() {
	int t;
	scanf("%d", &t);
	while (t--) {
		scanf("%d%d", &n, &m);
		for (int i = 0; i < n; ++i) scanf("%s", g[i]);
		bfs1();
		int ans = bfs2();
		if (ans == -1) printf("IMPOSSIBLE\n");
		else printf("%d\n", ans);
	}
	return 0;
}


posted @ 2018-01-27 14:22  不想吃WA的咸鱼  阅读(161)  评论(0编辑  收藏  举报