可以标记下每个点被燃烧的时间点,这样只要在这个时间点前到达的话,就可以走到这个点。两次BFS(),感觉真是太奇妙了。还有坑点,就是这地方有草,但Sample Input
2
4 4
####
#JF#
#..#
#..#
3 3
###
#J.
#.F
Sample Output
3
IMPOSSIBLE
是可能烧不到,一定要注意这种情况,就是标记能不能烧到
#include<iostream>
#include<cstdio>
#include<cstring>
#include<queue>
#include<algorithm>
using namespace std;
char map[1005][1005];
int vis[1005][1005];
int time1[1005][1005];//火到达这点的时间;
int n, m;
int a, b;
int dx[] = { 1,-1,0,0 };
int dy[] = { 0,0,-1,1 };
struct node {
int x, y;
int time;
};
int bfs() {
node now, next;
queue<node>q;
memset(vis, 0, sizeof(vis));
now.x = a, now.y = b, now.time = 0;
vis[a][b] = 1;
q.push(now);
while (!q.empty()) {
now = q.front();
q.pop();
if (now.x == 0 || now.x == n-1 || now.y == 0 || now.y == m-1) {
return now.time+1;
}
next.time = now.time + 1;
for (int i = 0; i < 4; i++) {
next.x = now.x + dx[i];
next.y = now.y + dy[i];
if (next.x >= 0 && next.x < n&&next.y >= 0 && next.y<m&&map[next.x][next.y] == '.' && !vis[next.x][next.y] && next.time<time1[next.x][next.y])
{
vis[next.x][next.y] = 1;
q.push(next);
}
}
}
return -1;
}
int main() {
int t;
cin >> t;
memset(vis, 0, sizeof(vis));
while (t--) {
memset(time1, -1, sizeof(time1));
cin >> n >> m;
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
cin >> map[i][j];
}
}
queue<node>q;
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
if (map[i][j] == 'J') {
a = i;
b = j;
}
else if (map[i][j] == 'F') {
node now;
now.x = i, now.y = j;
time1[i][j] = 0;
q.push(now);
vis[now.x][now.y] = 1;
}
}
}
node aa, next;
while (!q.empty()) {
aa = q.front();
q.pop();
for (int i = 0; i < 4; i++) {
next.x = aa.x + dx[i];
next.y = aa.y + dy[i];
if (vis[next.x][next.y]||next.x < 0 || next.x >= n || next.y<0 && next.y>=m || map[next.x][next.y] == '#') {
continue;
}
vis[next.x][next.y] = 1;
time1[next.x][next.y] = time1[aa.x][aa.y] + 1;
q.push(next);
}
}
int ans = bfs();
if (ans == -1)
printf("IMPOSSIBLE\n");
else
printf("%d\n", ans);
}
}