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.

Time & Space Complexity

Time Complexity
โฑ๏ธ
O(T ร— m ร— n)

T is the maximum waiting time, mร—n for BFS and fire simulation each iteration

n
2n
โœ“ Linear Growth
Space Complexity
O(m ร— n)

Grid storage and BFS queue space

n
2n
โšก 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
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