Fire!
InterviewTime limit1sMemory limit256 MB
Given a grid with walls, one starting cell, and burning cells, find the earliest minute Jihoon can step off the edge, given the fire spreads one cell per minute.
- Level
Medium6 of 10
- Topics
- BFS, Graph, Simulation, Matrix
- Solved
- No attempts yet
Problem
Jihoon is trapped inside a maze, and a fire is spreading through it. Determine whether Jihoon can escape the maze before the fire reaches him, and if so, the earliest time at which he can escape.
Each minute, both Jihoon and the fire move one cell in one of the four orthogonal directions (never diagonally). Each minute, the fire spreads from every burning cell to its four neighbouring cells. Neither Jihoon nor the fire can move through walls. Jihoon cannot move into a cell that is already on fire or that the fire spreads into during the same minute.
Jihoon escapes by moving out of the maze from a cell on its edge: if Jihoon is on an edge cell at some minute, he can move outside on the next minute. Jihoon starts at his initial position at minute 0.
Input
The first line contains two integers and separated by a space (), where is the number of rows and the number of columns of the maze.
Each of the following lines gives one row of the maze. The characters mean:
#: a wall.: a passable empty cellJ: Jihoon's starting position (a passable cell)F: a cell that is on fire
Exactly one J appears in the input.
Output
If Jihoon cannot escape the maze before the fire reaches him, print IMPOSSIBLE. Otherwise, print the earliest escape time (the minute at which Jihoon moves out of the maze).