Fire!

UVA - 11624 Fire! 双向BFS追击问题-LMLPHP

Joe works in a maze. Unfortunately, portions of the maze have caught 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

双向BFS。这题会被样例误导比较坑。。F点其实可以有多个。把J和someF分别加入两个队列,先扩展F点,把一步之内的点标记下,再扩展J,使得F可以影响J的路线。当J到达边界即逃脱,否则被#墙及F点围堵Fire。。

#include<stdio.h>
#include<string.h>
#include<queue>
using namespace std; char a[][];
int b[][];
int t[][]={{,},{,},{-,},{,-}}; struct Node{
int x,y,s;
}node; int main()
{
int tt,n,m,i,j;
scanf("%d",&tt);
while(tt--){
scanf("%d%d",&n,&m);
queue<Node> qj,qf;
memset(a,,sizeof(a));
memset(b,,sizeof(b));
for(i=;i<n;i++){
getchar();
scanf("%s",a[i]);
for(j=;j<m;j++){
if(a[i][j]=='J'){
b[i][j]=;
node.x=i;
node.y=j;
node.s=;
qj.push(node);
}
if(a[i][j]=='F'){
b[i][j]=;
node.x=i;
node.y=j;
node.s=;
qf.push(node);
}
}
}
int f=;
while(qj.size()){
int ss=qf.front().s;
while(qf.size()&&ss==qf.front().s){
for(i=;i<;i++){
int tx=qf.front().x+t[i][];
int ty=qf.front().y+t[i][];
if(tx<||ty<||tx>=n||ty>=m) continue;
if(a[tx][ty]=='#') continue;
if(b[tx][ty]==){
b[tx][ty]=;
node.x=tx;
node.y=ty;
node.s=qf.front().s+;
qf.push(node);
}
}
qf.pop();
}
int sss=qj.front().s;
while(qj.size()&&sss==qj.front().s){
for(i=;i<;i++){
int tx=qj.front().x+t[i][];
int ty=qj.front().y+t[i][];
if(tx<||ty<||tx>=n||ty>=m){
f=qj.front().s+;
break;
}
if(a[tx][ty]=='#') continue;
if(b[tx][ty]==){
b[tx][ty]=;
node.x=tx;
node.y=ty;
node.s=qj.front().s+;
qj.push(node);
}
}
if(f!=) break;
qj.pop();
}
if(f!=) break;
}
if(f==) printf("IMPOSSIBLE\n");
else printf("%d\n",f);
}
return ;
}
05-11 15:53