Description
Joe works in a maze. Unfortunately, portions of the maze havecaught on fire, and the owner of the maze neglected to create a fire escape plan. Help Joe escape the maze.Given Joe’s location in the maze and which squares of the maze are on fire, you must determine whether Joe can exit the maze before the fire reaches him, and how fast he can do it. Joe and the fire each move one square per minute, vertically or horizontally (not diagonally). The fire spreads all four directions from each square that is on fire. Joe may exit the maze from any
square that borders the edge of the maze. Neither Joe nor the fire may enter a square that is occupied by a wall.
Input
The first line of input contains a single integer, the number of test
cases to follow. The first line of each test case contains the two
integers R and C, separated by spaces, with 1 ≤ R, C ≤ 1000. The
following R lines of the test case each contain one row of the maze. Each of these lines contains exactly
C characters, and each of these characters is one of:
• #, a wall
• ., a passable square
• J, Joe’s initial position in the maze, which is a passable square
• F, a square that is on fire
There will be exactly one J in each test case.
Output
For each test case, output a single line containing ‘IMPOSSIBLE’ if Joe cannot exit the maze before the
fire reaches him, or an integer giving the earliest time Joe can safely exit the maze, in minutes.
Sample Input
2
4 4
#JF#
#…#
#…#
3 3
#J.
#.F
Sample Output
3
IMPOSSIBLE
Code
#include <iostream>
#include <stdio.h>
#include <queue>
#include <string.h>
#include <math.h>
#include <vector>
using namespace std;
const int MAXN=1e3+1;
int map[MAXN][MAXN];
struct node{
int x,y;
int step;
int is_human;
node(int i=0,int j=0,int k=0,int f=0){
x=i;
y=j;
step=k;
is_human=f;
}
};
int d1[4]={0,0,-1,1};
int d2[4]={-1,1,0,0};
int R,C;
inline bool is_in(int x,int y){
return x>=0&&x<R&&y>=0&&y<C;
}
int main(){
//freopen("/Users/guoyu/Desktop/algorithm/in.txt", "r", stdin);
int T;scanf("%d",&T);
while(T--){
scanf("%d%d",&R,&C);
char s[MAXN];int sx,sy;
queue<node> q;
for(int i=0;i<R;i++){
scanf("%s",s);
for(int j=0;j<C;j++){
map[i][j]=1;
if(s[j]=='.') map[i][j]=0;
if(s[j]=='J'){
sx=i;sy=j;
}
if(s[j]=='F'){
q.push(node(i,j));
}
}
}
q.push(node(sx,sy,0,1));
int ans=-1;
while(!q.empty()){
node tmp=q.front();q.pop();
if(tmp.is_human&&(tmp.x==0||tmp.y==0||tmp.x==R-1||tmp.y==C-1)){
ans=tmp.step+1;break;
}
for(int i=0;i<4;i++){
int nx=tmp.x+d1[i],ny=tmp.y+d2[i];
if(is_in(nx,ny)&&!map[nx][ny]){
map[nx][ny]=1;
q.push(node(nx,ny,tmp.step+1,tmp.is_human));
}
}
}
if(ans>0) printf("%d\n",ans);
else printf("IMPOSSIBLE\n");
}
return 0;
}