Problem Description
Given an m x n grid where 0 represents grass, 1 represents fire, and 2 represents a wall, you start at the top-left cell (0,0) and must reach the safehouse at the bottom-right cell (m-1, n-1) by moving to adjacent grass cells. After each move you make, all fire cells spread to their adjacent (non-wall) cells. Determine the maximum number of minutes you can wait in your initial cell before starting your journey such that you still safely reach the safehouse. If it is impossible to reach the safehouse even when moving immediately, return -1. If you can always reach safely regardless of the waiting time, return 10^9.
Key Insights
- Compute the earliest time each cell will catch fire by performing a multi-source BFS starting from all fire cells.
- Run a separate BFS for your movement starting from (0, 0) after a given waiting time, ensuring you move only into cells that haven’t yet caught fire. (For intermediate cells, you must arrive before the fire; for the destination, arriving at the same time as the fire is allowed.)
- Use binary search on the waiting time t (from 0 to 10^9) to determine the maximum delay for which escape is possible.
- Handle edge cases: if you cannot escape when moving immediately, return -1; if even with a delay of 10^9 you can escape, return 10^9.
Space and Time Complexity
Time Complexity: O(m * n * log(MaxTime)) where each BFS runs in O(m*n) and binary search takes O(log(MaxTime)) steps. Space Complexity: O(m * n) for the fire time grid and additional data structures used in BFS.
Solution
We first precompute the earliest time that fire reaches each cell using a multi-source BFS from all fire cells. For each candidate waiting time, we simulate your movement using BFS starting from cell (0,0) and checking that each visited cell is reached before the fire (or, in the case of the destination, no later than the fire arrival time). If you can safely reach the destination with a given waiting time, then it is feasible. We use binary search over possible waiting times to find the maximum delay for which escape is possible. Special conditions are handled by returning -1 if immediate escape is impossible, or 10^9 if even a long delay is tolerated.