Escape the Spreading Fire - Problem
Escape the Spreading Fire
You find yourself trapped in a burning field represented by a 2D grid, where you must escape from the top-left corner (0,0) to a safehouse at the bottom-right corner while avoiding the spreading flames!
๐ฑ
๐ฅ
๐งฑ
The challenge: What's the maximum time you can wait before starting your escape?
Game Rules:
โข You can move to adjacent grass cells (up, down, left, right)
โข After each of your moves, fire spreads to all adjacent non-wall cells
โข You need to reach the safehouse before being caught by fire
โข If you can reach safely regardless of wait time, return
โข If escape is impossible, return
Victory Condition: Even if fire reaches the safehouse right after you arrive, you still win! ๐ฏ
You find yourself trapped in a burning field represented by a 2D grid, where you must escape from the top-left corner (0,0) to a safehouse at the bottom-right corner while avoiding the spreading flames!
๐ฑ
0 = Grass (safe to walk on)๐ฅ
1 = Fire (spreads every minute)๐งฑ
2 = Wall (blocks both you and fire)The challenge: What's the maximum time you can wait before starting your escape?
Game Rules:
โข You can move to adjacent grass cells (up, down, left, right)
โข After each of your moves, fire spreads to all adjacent non-wall cells
โข You need to reach the safehouse before being caught by fire
โข If you can reach safely regardless of wait time, return
109โข If escape is impossible, return
-1Victory Condition: Even if fire reaches the safehouse right after you arrive, you still win! ๐ฏ
Input & Output
example_1.py โ Basic Escape
$
Input:
grid = [[0,2,0,0,0,0,0],[0,0,0,2,2,1,0],[0,2,0,0,1,2,0],[0,0,2,2,2,0,2],[0,0,0,0,0,0,0]]
โบ
Output:
3
๐ก Note:
You can wait 3 minutes at the starting position before moving. The fire will spread but you can still find a safe path to the bottom-right corner by going around the walls and avoiding the spreading flames.
example_2.py โ Impossible Escape
$
Input:
grid = [[0,0,0,0],[0,1,2,0],[0,2,0,0]]
โบ
Output:
-1
๐ก Note:
The fire will spread and block all possible paths to the destination. No matter when you start moving, you cannot reach the safehouse safely.
example_3.py โ Unlimited Time
$
Input:
grid = [[0,0,0],[2,2,0],[0,0,0]]
โบ
Output:
1000000000
๐ก Note:
There is no fire in the grid (only walls and grass), so you can wait indefinitely and still reach the safehouse. The walls don't block your optimal path.
Time & Space Complexity
Time Complexity
O(T ร m ร n)
T is the maximum waiting time, mรn for BFS and fire simulation each iteration
โ Linear Growth
Space Complexity
O(m ร n)
Grid storage and BFS queue space
โก Linearithmic Space
Constraints
- m == grid.length
- n == grid[i].length
- 2 โค m, n โค 300
- 4 โค m ร n โค 2 ร 104
- grid[i][j] is either 0, 1, or 2
- grid[0][0] == grid[m-1][n-1] == 0
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code