先对大火燃烧的过程BFS一遍,并记录大火烧到当前位置所需时间
在对joe行走过程BFS一遍即可
代码如下:
#include <queue>
#include <cstring>
#include <cstdio>
#include <iostream>
#include <algorithm>
#define MAXN 1010
#define LL long long
using namespace std;
int fire_num, r, c;
int g[MAXN][MAXN];
bool vis[MAXN][MAXN];
struct Position {
int x, y;
}joe_position, fire_position[MAXN];
struct Node {
int x, y, time;
};
queue<Node> p, q;
void BFS_fire(void) {
while(!p.empty()) //使用的时候不要忘了清空
p.pop();
Node cur;
for(int i=0; i<fire_num; ++i) {
cur.x = fire_position[i].x;
cur.y = fire_position[i].y;
cur.time = 0;
g[cur.x][cur.y] = 0;
p.push(cur);
vis[cur.x][cur.y] = true;
}
while(!p.empty()) {
cur = p.front();
p.pop();
Node tmp;
int x_tmp = cur.x;
int y_tmp = cur.y;
g[x_tmp][y_tmp] = cur.time; //有火烧到的位置,更新其值为火烧到这里所需时间
if(x_tmp-1>=0 && g[x_tmp-1][y_tmp]==-1 && !vis[x_tmp-1][y_tmp]) { //向左判断
tmp.x = x_tmp-1;
tmp.y = y_tmp;
tmp.time = cur.time+1;
p.push(tmp);
vis[x_tmp-1][y_tmp] = true;
}
if(x_tmp+1<r && g[x_tmp+1][y_tmp]==-1 && !vis[x_tmp+1][y_tmp]) { //向右判断
tmp.x = x_tmp+1;
tmp.y = y_tmp;
tmp.time = cur.time+1;
p.push(tmp);
vis[x_tmp+1][y_tmp] = true;
}
if(y_tmp-1>=0 && g[x_tmp][y_tmp-1]==-1 && !vis[x_tmp][y_tmp-1]) { //向下判断
tmp.x = x_tmp;
tmp.y = y_tmp-1;
tmp.time = cur.time+1;
p.push(tmp);
vis[x_tmp][y_tmp-1] = true;
}
if(y_tmp+1<c && g[x_tmp][y_tmp+1]==-1 && !vis[x_tmp][y_tmp+1]) { //向上判断
tmp.x = x_tmp;
tmp.y = y_tmp+1;
tmp.time = cur.time+1;
p.push(tmp);
vis[x_tmp][y_tmp+1] = true;
}
}
}
bool judge_joe(int x, int y, Node &cur, Node &tmp) { //判断joe是否可以走向这个位置
if(!vis[x][y] && (g[x][y]==-1 || g[x][y]-cur.time>1)) {
tmp.x = x;
tmp.y = y;
tmp.time = cur.time+1;
q.push(tmp);
vis[x][y] = true;
}
}
int BFS_joe(int x, int y) {
while(!q.empty())
q.pop();
struct Node cur;
cur.x = x;
cur.y = y;
cur.time = 0;
q.push(cur);
while(!q.empty()) {
cur = q.front();
q.pop();
int x_tmp = cur.x;
int y_tmp = cur.y;
struct Node tmp;
if(x_tmp-1<0 || x_tmp+1>=r || y_tmp-1<0 || y_tmp+1>=c) //已经走出迷宫
return cur.time+1;
judge_joe(x_tmp-1, y_tmp, cur, tmp);
judge_joe(x_tmp+1, y_tmp, cur, tmp);
judge_joe(x_tmp, y_tmp-1, cur, tmp);
judge_joe(x_tmp, y_tmp+1, cur, tmp);
}
return -1;
}
int main(void) {
int T, ans;
char ch;
scanf("%d", &T);
while(T--) {
scanf("%d%d", &r, &c);
fire_num = 0;
for(int i=0; i<r; ++i) {
getchar();
for(int j=0; j<c; ++j) {
ch = getchar();
if(ch == 'J') {
joe_position.x = i;
joe_position.y = j;
g[i][j] = 0;
}
else if(ch == 'F') {
fire_position[fire_num].x = i;
fire_position[fire_num++].y = j;
g[i][j] = 0;
}
else if(ch == '.')
g[i][j] = -1;
else g[i][j] = -2;
}
}
memset(vis, 0, sizeof(vis));
BFS_fire();
memset(vis, 0, sizeof(vis));
ans = BFS_joe(joe_position.x, joe_position.y);
if(ans == -1)
cout << "IMPOSSIBLE" << endl;
else cout << ans << endl;
}
return 0;
}