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.
- #, 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
题目大意:
给定一个M x N的矩阵,其中“J”为人,“F”为火,“#”为墙,“.”为空地,人和火在每个时间单位内都可以移动一格,问这个人能不能在大活吞噬整个地图之前跑出去?
注意事项:
①J有可能被封在四面墙里边,这种情况下,虽然火永远烧不到他,不过也视为IMPOSSIBLE。
②火和人都是不能穿墙的。
③火不一定只有一处,也可能一处也没有。
解题思路:
两次bfs,先对火bfs,定义number数组记录火到达每个点所需要的时间。
再对人bfs,如果火比自己先到,那么这条路不能走。
代码如下:
import java.util.*;
public class Main
{
public static char[][] map = new char[1001][1001];
public static int[][] number = new int[1001][1001];
public static Scanner in = new Scanner(System.in);
public static int x_go[] = {0,0,1,-1};
public static int y_go[] = {1,-1,0,0};
public static int hang,lie;
public static Room J;
public static Queue<Room>q = new LinkedList<Room>();
public static void main(String[] args)
{
int t = in.nextInt();
while((t--)>0)
{
inint();
bfs();
int answer = bfs2();
if(answer>0)System.out.println(answer);
else System.out.println("IMPOSSIBLE");
}
}
public static int bfs2()
{
q.clear();
q.add(J);
while(!q.isEmpty())
{
Room r = q.remove();
int temx,temy;
for(int i=0 ; i<4 ; i++)
{
temx = r.x + x_go[i];
temy = r.y + y_go[i];
if(temx<0 || temx==hang || temy<0 || temy==lie) return r.step;
if(map[temx][temy]=='#')continue;
if(number[temx][temy]<0)continue;
if(number[temx][temy]<=r.step+1 && number[temx][temy]!=0)continue;
number[temx][temy] = -1;
q.add(new Room(temx,temy,r.step+1));
}
}
return -1;
}
public static void bfs()
{
while(!q.isEmpty())
{
Room r = q.poll();
int temx,temy;
for(int i=0 ; i<4 ; i++)
{
temx = r.x + x_go[i];
temy = r.y + y_go[i];
if(temx<0 || temx==hang) continue;
if(temy<0 || temy==lie)continue;
if(map[temx][temy]=='#')continue;
if(number[temx][temy]>0)continue;
number[temx][temy] = r.step+1;
q.add(new Room(temx,temy,r.step+1));
}
}
}
public static void inint()
{
q.clear();
hang = in.nextInt();
lie = in.nextInt();
String str;
for(int i=0 ; i<hang ; i++)
{
str = in.next();
for(int j=0 ; j<lie ; j++)
{
number[i][j] = 0;
map[i][j] = str.charAt(j);
if(map[i][j]=='J')J = new Room(i,j,1);
if(map[i][j]=='F')
{
q.add(new Room(i,j,1));
number[i][j] = 1;
}
}
}
}
}
class Room
{
int x,y,step;
public Room(int x,int y,int step)
{
this.x = x;
this.y = y;
this.step = step;
}
}