大火蔓延的迷宫(Fire!, UVa 11624)
白书5.1 例题1
Code:
#include <cstdio>
#include <cstring>
#include <string>
#include <queue>
using namespace std;
const int N = 1000 + 5;
char mp[N][N];
bool vis[N][N];
int T, R, C;
struct node {
int x, y, step, state; //state 0是火 1是人
node(int x, int y, int step, int state) : x(x), y(y), step(step), state(state) {}
};
int dx[4] = {-1, 0, 1, 0};
int dy[4] = {0, 1, 0, -1};
int bfs() {
queue<node> Q;
for (int i = 1; i <= R; i++)
for (int j = 1; j <= C; j++)
if (mp[i][j] == 'F') {
Q.push(node(i, j, 0, 0));
vis[i][j] = true;
}
for (int i = 1; i <= R; i++)
for (int j = 1; j <= C; j++)
if (mp[i][j] == 'J') {
Q.push(node(i, j, 0, 1));
vis[i][j] = true;
}
while (!Q.empty()) {
node now = Q.front();
Q.pop();
if (now.state == 1 && (now.x == 1 || now.x == R || now.y == 1 || now.y == C)) return now.step + 1;
for (int i = 0; i < 4; i++) {
int x = now.x + dx[i], y = now.y + dy[i];
if (x < 1 || x > R || y < 1 || y > C || vis[x][y] || mp[x][y] == '#') continue;
Q.push(node(x, y, now.step + 1, now.state));
vis[x][y] = true;
}
}
return 0;
}
int main() {
#ifdef ONLINE_JUDGE
#else
freopen("in.txt", "r", stdin);
#endif
scanf("%d", &T);
while (T--) {
scanf("%d%d", &R, &C);
memset(mp, '\0', sizeof(mp));
memset(vis, 0, sizeof(vis));
for (int i = 1; i <= R; i++)
scanf("%s", mp[i] + 1);
int ans = bfs();
if (ans) printf("%d\n", ans);
else printf("IMPOSSIBLE\n");
}
return 0;
}