796. Outrun the Fire

A warehouse floor is an m x n grid grid. A cell is 0 for open floor, 1 for a cell that is already burning, or 2 for a concrete pillar. Every minute, fire spreads from each burning cell to its up, down, left and right neighbours that are open floor. Pillars never burn and block both fire and walking.

A guard stands in the top-left cell and must reach the exit in the bottom-right cell; both are open floor. The guard may first wait in place for any whole number of minutes, then walks, moving one cell up, down, left or right per minute. A cell the guard enters at the same minute the fire reaches it is fatal, except the exit, where arriving together with the fire is fine. Return the largest number of minutes the guard can wait and still escape, -1 if escaping is impossible even with no wait, or 1000000000 if the guard can wait forever and still escape.

Example 1

Input:
grid = [[0,0,0,0],[1,2,2,0]]
Output:
0
Explanation:

The cell below the guard is burning, so the start cell ignites after one minute and the guard must leave immediately; walking along the top row keeps ahead of the flames, so the answer is 0.

Example 2

Input:
grid = [[0,0,0,0,0],[0,0,2,0,0],[0,2,0,0,0],[0,1,2,0,0]]
Output:
3
Explanation:

The fire is trapped in a pocket and has to crawl up the left column, reaching the start cell at minute 4. The guard can wait 3 minutes and still stays ahead of the front all the way to the exit, so the answer is 3.

Example 3

Input:
grid = [[0,0,0,0],[2,2,2,0],[1,2,0,0]]
Output:
1000000000
Explanation:

The fire is walled in (its neighbours above and to the right are walls), so waiting never hurts and the answer is 1000000000.

Constraints

  • 1 ≤ m, n ≤ 300 and m * n ≥ 2
  • grid[i][j] is 0, 1 or 2
  • grid[0][0] = grid[m-1][n-1] = 0
  • The grid may contain no burning cell at all.

How this problem is judged

Answers
Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
Time per case
Python 600 msC++ 150 msJava 300 msJavaScript 300 msTypeScript 300 ms

Expected complexity

Time
O(m * n * log(m * n))
Space
O(m * n)

What the author was aiming for. Your own solution is not measured against it.

Asked in an interview

Were you asked this in an interview? Say where, anonymously.

Code
Loading the editor…