Problem B: Fire!
![](http://uva.onlinejudge.org/external/116/p11624.png)
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 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
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,火先扩展一层,人再走一层,一直这样走下去。
感想:这题水,但是一直卡死在细节上。一直以为将bfs_init放在for的外面就可以避免人在同一步之下火多走。结果发现还是不能避免。另外,每次扩展出一步就要将该步变成墙,否则还是不能避免重复走。
AC代码:
#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;
int dir[4][2]={{1,0},{-1,0},{0,1},{0,-1}};
char mp[1005][1005];
struct point{
int x,y;
}que[11000009],que1[11000009];
int mov[1005][1005];
int rear,front,n,m;
int rear1,front1;
void bfs_init(){
int p=rear1;
while(front1<p){//走一层而已
point tp=que1[front1++];
for(int i=0;i<4;i++){
int xx=tp.x+dir[i][0];
int yy=tp.y+dir[i][1];
if(xx>=0&&xx<n&&yy>=0&&yy<m&&mp[xx][yy]!='#'){
mp[xx][yy]='#';
que1[rear1].x=xx;
que1[rear1].y=yy;
rear1++;
}
}
}
}
int bfs(){
int step=0;
while(front<rear){
point tp=que[front++];
if(tp.x==0||tp.y==0||tp.x==n-1||tp.y==m-1)return mov[tp.x][tp.y]+1;
if(step==mov[tp.x][tp.y]){bfs_init();step++;}//step代表层,一层火只走一次
for(int i=0;i<4;i++){
int xx=tp.x+dir[i][0];
int yy=tp.y+dir[i][1];
if(mp[xx][yy]!='#'){
mp[xx][yy]='#';//此处一定要马上变成墙,这样否则会出现重复走的现象
mov[xx][yy]=mov[tp.x][tp.y]+1;
que[rear].x=xx;
que[rear].y=yy;
rear++;
}
}
mp[tp.x][tp.y]='#';
}
return -1;
}
int main(){
int T;
scanf("%d",&T);
while(T--){
memset(mov,0,sizeof(mov));
scanf("%d%d",&n,&m);
for(int i=0;i<n;i++)
scanf("%s",mp[i]);
rear1=front1=rear=front=0;
for(int i=0;i<n;i++)
for(int j=0;j<m;j++)
if(mp[i][j]=='F'){que1[rear1].x=i;que1[rear1].y=j;rear1++;mp[i][j]='#';}
else if(mp[i][j]=='J'){que[rear].x=i;que[rear].y=j;rear++;mov[i][j]=0;}
int ans=bfs();
if(ans==-1)puts("IMPOSSIBLE");
else printf("%d\n",ans);
}
}