两次BFS,第一次记录下每个点着火的时间,第二次BFS时直接和时间比较,如果在着火点之前到,则可以继续入栈。。
注意push的同时更新used数组,忘记更新会造成tle
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <queue>
#define MAXN 1100
#define INF 10000000
using namespace std;
struct Point {
int r,c;
int step;
};
int r,c;
queue<Point> q;
char mp[MAXN][MAXN];
int time[MAXN][MAXN];
int sx,sy;
int dir[4][2] = {{1,0},{-1,0},{0,1},{0,-1}};
bool used[MAXN][MAXN];
int main() {
int T;
// freopen("out.txt","w",stdout);
scanf("%d",&T);
while(T--) {
scanf("%d%d",&r,&c);
while(!q.empty()) q.pop();
memset(used,0,sizeof(used));
for(int i = 0;i < r;i++)
for(int j = 0;j < c;j++)
time[i][j] = INF;
for(int i = 0;i < r;i++)
scanf("%s",mp+i);
for(int i = 0;i < r;i++)
for(int j = 0;j < c;j++) {
if(mp[i][j] == 'F') {
q.push((Point){i,j,0});
used[i][j] = true;
time[i][j] = 0;
}
}
while(!q.empty()) {
Point p = q.front();
q.pop();
for(int i = 0;i < 4;i++) {
int xx = p.r+dir[i][0];
int yy = p.c+dir[i][1];
if(xx<0||xx>=r||yy<0||yy>=c) continue;
if(used[xx][yy]) continue;
if(mp[xx][yy] != '#') {
q.push((Point){xx,yy,p.step+1});
used[xx][yy] = true;
time[xx][yy] = p.step+1;
}
}
}
while(!q.empty()) q.pop();
memset(used,0,sizeof(used));
for(int i = 0;i < r;i++)
for(int j = 0;j < c;j++) {
if(mp[i][j] == 'J') {
q.push((Point){i,j,0});
used[i][j] = true;
}
}
int res = INF;
while(!q.empty()) {
Point p = q.front();
q.pop();
for(int i = 0;i < 4;i++) {
int xx = p.r+dir[i][0];
int yy = p.c+dir[i][1];
if(xx<0||xx>=r||yy<0||yy>=c) {
res = p.step+1;
while(!q.empty()) q.pop();
break;
}
if(used[xx][yy]) continue;
if(mp[xx][yy] == '.') {
if(time[xx][yy] <= p.step+1) continue;
q.push((Point){xx,yy,p.step+1});
used[xx][yy] = true;
}
}
}
if(res == INF) printf("IMPOSSIBLE\n");
else printf("%d\n",res);
}
return 0;
}