Joe works in a maze. Unfortunately, portions of the maze have caught on fire, and the owner of the maze neglected to create a firee scape 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.
题意:
人要从迷宫中逃出去,在火到达之前,人只有一个,但火不止一个
思路:
BFS
可以用两个bfs来写,或者是像下面我写的一个bfs,但实质也是两个,一个是人的bfs,一个是火的bfs,细节部分在代码中标注
代码:
#include<stdio.h>
#include<queue>
#include<string.h>
#include<algorithm>
using namespace std;
int dir[4][2]= {1,0,-1,0,0,1,0,-1};
char a[1010][1010];
bool book[1010][1010];
struct node
{
int x,y,f,t;
} u,v;
int main()
{
int t;
scanf("%d",&t);
while(t--)
{
memset(book,0,sizeof(book));
int n,m;
scanf("%d %d",&n,&m);
for(int i=0; i<n; i++)
scanf("%s",a[i]);
queue<node>q;
node joe;
for(int i=0; i<n; i++) //不能走的路提前标记为1
{
for(int j=0; j<m; j++)
{
if(a[i][j]=='#')
{
book[i][j]=1;
}
else if(a[i][j]=='J')//人的位置
{
book[i][j]=1;
joe.x=i;
joe.y=j;
joe.f=0;//f=0表示人,f=1表示火
joe.t=0;//分钟数
}
else if(a[i][j]=='F')//火的位置
{
book[i][j]=1;
q.push((node){i,j,1,0});//先将所有的火入队列
}
}
}
q.push(joe);//在将火全部入队列后,最后 人 入队列
int ans=-1;
while(!q.empty())
{
u=q.front();
q.pop();
for(int i=0; i<4; i++)
{
v=u;
v.t++;
v.x=u.x+dir[i][0];
v.y=u.y+dir[i][1];
if(v.x>=0&&v.x<n&&v.y>=0&&v.y<m)//不越界
{
if(!book[v.x][v.y]) //没有走过
{
book[v.x][v.y]=1;
q.push(v);
}
}
else if(v.f==0)//人+越界=逃跑成功 bingo
{
ans=v.t;
break;
}
}
if(ans!=-1)
break;
}
if(ans==-1)
printf("IMPOSSIBLE\n");
else
printf("%d\n",ans);
}
return 0;
}