Problem B: Fire!

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 Specification
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 integersR and C, separated by spaces, with 1 <= R,C <= 1000. The followingR lines of the test case each contain one row of the maze. Each of these lines contains exactlyC 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
Sample Input
2 4 4 #### #JF# #..# #..# 3 3 ### #J. #.F
Output Specification
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.Output for Sample Input
3 IMPOSSIBLE
思路:两次BFS,一次对人,一次对火找到达各个点的最小时间
#include<stdio.h>
#include<string.h>
#include<queue>
#include<algorithm>
using namespace std;
struct node
{
int x,y,time;
};
char map[1010][1010];
int vis[1010][1010];
int dis[1010][1010];
int n,m;
int dx[]={0,0,-1,1};
int dy[]={-1,1,0,0};
queue<node>q;
void bfs_fire()
{
node next,now;
while(!q.empty())
{
now=q.front();
q.pop();
for(int i=0;i<4;i++)
{
int sx=now.x+dx[i];
int sy=now.y+dy[i];
if(sx>=0&&sx<n&&sy>=0&&sy<m&&(map[sx][sy]=='.'||map[sx][sy]=='J')&&!vis[sx][sy])
{
vis[sx][sy]=1;
next.x=sx;
next.y=sy;
next.time=now.time+1;
dis[sx][sy]=next.time;//记录火到达的最短时间
q.push(next);
}
}
}
}
int bfs_men(node p)
{
while(!q.empty())
q.pop();
node now,next;
int i;
q.push(p);
vis[p.x][p.y]=1;
while(!q.empty())
{
now=q.front();
q.pop();
if(now.x<=0||now.y<=0||now.x==n-1||now.y==m-1)
return now.time;//人到达迷宫边缘
for(i=0;i<4;i++)
{
int ex=now.x+dx[i];
int ey=now.y+dy[i];
if(ex>=0&&ey>=0&&ex<n&&ey<m&&(map[ex][ey]=='.'||map[ex][ey]=='J')&&!vis[ex][ey])
{
if(dis[ex][ey]<=now.time+1)//人到达的时间大于火到达的时间
continue;
vis[ex][ey]=1;
next.x=ex;
next.y=ey;
next.time=now.time+1;
q.push(next);
}
}
}
return -1;
}
int main()
{
int t,i,j;
node temp,p;
scanf("%d",&t);
while(t--)
{
scanf("%d%d",&n,&m);
while(!q.empty())
q.pop();
memset(vis,0,sizeof(vis));
for(i=0;i<n;i++)
{
scanf("%s",map[i]);
for(j=0;j<m;j++)
{
dis[i][j]=1100000000;//刚开始这地方用memset一直WA。。。。。
if(map[i][j]=='F')
{
temp.x=i;
temp.y=j;
temp.time=0;
q.push(temp);
vis[i][j]=1;
dis[i][j]=0;
}
if(map[i][j]=='J')
{
p.x=i;
p.y=j;
p.time=0;
}
}
}
bfs_fire();
memset(vis,0,sizeof(vis));
int ans;
ans=bfs_men(p);
if(ans>=0)
printf("%d\n",ans+1);
else
printf("IMPOSSIBLE\n");
}
return 0;
}