caught on re, and the owner of the maze neglected to create a re
escape plan. Help Joe escape the maze.
Given Joe's location in the maze and which squares of the maze
are on re, you must determine whether Joe can exit the maze before
the re reaches him, and how fast he can do it.
Joe and the re each move one square per minute, vertically or
horizontally (not diagonally). The re spreads all four directions
from each square that is on re. Joe may exit the maze from any
square that borders the edge of the maze. Neither Joe nor the re
may enter a square that is occupied by a wall.
Input
The rst line of input contains a single integer, the number of test
cases to follow. The rst 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 re
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
Sample Input
2
4 4
####
#JF#
#..#
#..#
3 3
###
#J.
#.F
Sample Output
3
IMPOSSIBLE
#include <iostream> #include <cstdio> #include <cstring> #include <cstdlib> #include <cmath> #include <queue> using namespace std; char pi[1000][1000]; int vis[1000][1000]; int fire[1000][1000]; struct que { int x,y,t; }temp; int dir[4][2]={0,1,1,0,0,-1,-1,0}; int main() { int T,m,n,sx=0,sy=0,flag; queue<que> q; //std::ios::sync_with_stdio(false); //std::cin.tie(0); cin>>T; while(T--) { cin>>n>>m; flag=0; memset(vis,0,sizeof(vis)); for(int i=0;i<n;i++) { for(int j=0;j<m;j++) { cin>>pi[i][j]; fire[i][j]=999999999; } } while(!q.empty())q.pop(); for(int i=0;i<n;i++) { for(int j=0;j<m;j++) { if(pi[i][j]=='J')sx=i,sy=j; else if(pi[i][j]=='F') { fire[i][j]=0; temp.x=i,temp.y=j,temp.t=0; q.push(temp); } else if(pi[i][j]=='#')vis[i][j]=1; } } while(!q.empty()) { for(int k=0;k<4;k++) { int tx=q.front().x+dir[k][0]; int ty=q.front().y+dir[k][1]; if(tx<0||ty<0||tx>=n||ty>=m||vis[tx][ty]||q.front().t+1>=fire[tx][ty])continue; temp.x=tx,temp.y=ty,temp.t=q.front().t+1; fire[tx][ty]=temp.t; q.push(temp); } q.pop(); } while(!q.empty())q.pop(); temp.x=sx,temp.y=sy,temp.t=0; vis[sx][sy]=1; q.push(temp); while(!q.empty()) { if(!q.front().x||!q.front().y||q.front().x==n-1||q.front().y==m-1) { flag=1; cout<<q.front().t+1<<endl; break; } for(int i=0;i<4;i++) { int tx=q.front().x+dir[i][0]; int ty=q.front().y+dir[i][1]; if(tx<0||ty<0||tx>=n||ty>=m||vis[tx][ty]||fire[tx][ty]<=q.front().t+1)continue; temp.x=tx,temp.y=ty,temp.t=q.front().t+1; vis[tx][ty]=1; q.push(temp); } q.pop(); } if(flag==0)cout<<"IMPOSSIBLE"<<endl; } }