标签:
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <cmath>
#include <cstdlib>
#include <queue>
using namespace std;
const int N = 1005;
typedef long long ll;
int n, m;
int dir[4][2] = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}};
struct Node{
int x, y, d;
bool operator < (const Node& x) const {
return d > x.d;
}
};
Node s;
int cnt;
int fire[N][N];
queue<Node> Q;
priority_queue<Node> Q2;
char map[N][N];
int BFS_F() {
while (!Q.empty()) {
Node p = Q.front();
Q.pop();
int px, py;
for (int i = 0; i < 4; i++) {
px = p.x + dir[i][0], py = p.y + dir[i][1];
if (px < 0 || py < 0 || px >= n || py >= m) continue;
if (map[px][py] == ‘#‘) continue;
map[px][py] = ‘F‘;
if (fire[px][py] > p.d + 1 || fire[px][py] == -1) {
fire[px][py] = p.d + 1;
Q.push((Node){px, py, p.d + 1});
}
}
}
}
int BFS() {
while (!Q2.empty()) {
Node p = Q2.top();
Q2.pop();
for (int i = 0; i < 4; i++) {
int px = p.x + dir[i][0], py = p.y + dir[i][1];
if (px < 0 || py < 0 || px >= n || py >= m) continue;
if (map[px][py] == ‘#‘ || map[px][py] == ‘J‘) continue;
if (fire[px][py] >= p.d + 2) {
if (px == 0 || py == 0 || px == n - 1 || py == m - 1) {
return p.d + 1;
}
map[px][py] = ‘J‘;
Q2.push((Node){px, py, p.d + 1});
}
}
}
return 0;
}
int main() {
int T;
scanf("%d", &T);
while (T--) {
cnt = 0;
memset(fire, -1, sizeof(fire));
while (!Q.empty()) Q.pop();
while (!Q2.empty()) Q2.pop();
scanf("%d %d\n", &n, &m);
int flag = 0, flag2 = 0;
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
scanf("%c", &map[i][j]);
if (map[i][j] == ‘J‘) {
if (i == 0 || j == 0 || i == n - 1 || j == m - 1) {
flag = 1;
}
Q2.push((Node){i, j, 0});
} else if (map[i][j] == ‘F‘) {
flag2 = 1;
fire[i][j] = 0;
Q.push((Node){i, j, 0});
}
}
getchar();
}
if (!flag2) memset(fire, 0x3f, sizeof(fire));
if (flag) {
printf("1\n");
continue;
}
BFS_F();
int B = BFS();
if (!B) {
printf("IMPOSSIBLE\n");
} else printf("%d\n", B + 1);
}
return 0;
}
版权声明:本文为博主原创文章,未经博主允许也可以转载,不过要注明出处哦。
标签:
原文地址:http://blog.csdn.net/llx523113241/article/details/47344797