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!

🌱 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 -1

Victory 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.

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
Asked in
25.0K Views
Medium Frequency
~15 min Avg. Time
850 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen