Escape the Spreading Fire - Problem

You are given a 0-indexed 2D integer array grid of size m x n which represents a field. Each cell has one of three values:

  • 0 represents grass
  • 1 represents fire
  • 2 represents a wall that you and fire cannot pass through

You are situated in the top-left cell (0, 0), and you want to travel to the safehouse at the bottom-right cell (m - 1, n - 1). Every minute, you may move to an adjacent grass cell. After your move, every fire cell will spread to all adjacent cells that are not walls.

Return the maximum number of minutes that you can stay in your initial position before moving while still safely reaching the safehouse. If this is impossible, return -1. If you can always reach the safehouse regardless of the minutes stayed, return 10^9.

Note that even if the fire spreads to the safehouse immediately after you have reached it, it will be counted as safely reaching the safehouse.

A cell is adjacent to another cell if the former is directly north, east, south, or west of the latter (i.e., their sides are touching).

Input & Output

Example 1 — Basic Fire Spread
$ 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: We can wait 3 minutes before starting. Fire spreads each minute, but we can still find a safe path to reach (4,6) within the time limit.
Example 2 — Impossible Path
$ Input: grid = [[0,0,0,0],[0,1,2,0],[0,2,0,0]]
Output: -1
💡 Note: There's no path from (0,0) to (2,3) that avoids both fire spread and walls, making escape impossible.
Example 3 — No Fire Threat
$ Input: grid = [[0,0,0],[2,2,0],[0,0,0]]
Output: 1000000000
💡 Note: No fire exists in the grid, so we can wait indefinitely before moving to the safehouse.

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

Visualization

Tap to expand
INPUT GRIDALGORITHMRESULT020001200200Start: (0,0) --> End: (2,3)Green=Grass, Red=Fire, Gray=Wall1Binary Search Delay2Simulate Fire Spread3BFS Path Search4Update Search RangeTime: O(log(mn) × mn)Space: O(mn)Maximum Delay3 minutesCan wait up to 3 minutesbefore starting escape• Return -1 if impossible• Return 10^9 if no fireKey Insight:Binary search works because if we can escape with delay T,we can escape with any delay less than T (monotonic property)TutorialsPoint - Escape the Spreading Fire | Binary Search + BFS
Asked in
Google 25 Amazon 18 Microsoft 12 Facebook 8
23.5K Views
Medium Frequency
~35 min Avg. Time
847 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