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

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

&nbsp;
Example 1:

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
Explanation: The figure above shows the scenario where you stay in the initial position for 3 minutes.
You will still be able to safely reach the safehouse.
Staying for more than 3 minutes will not allow you to safely reach the safehouse.

Example 2:

Input: grid = [[0,0,0,0],[0,1,2,0],[0,2,0,0]]
Output: -1
Explanation: The figure above shows the scenario where you immediately move towards the safehouse.
Fire will spread to any cell you move towards and it is impossible to safely reach the safehouse.
Thus, -1 is returned.


Example 3:

Input: grid = [[0,0,0],[2,2,0],[1,2,0]]
Output: 1000000000
Explanation: The figure above shows the initial grid.
Notice that the fire is contained by walls and you will always be able to safely reach the safehouse.
Thus, 109 is returned.


&nbsp;
Constraints:


	m == grid.length
	n == grid[i].length
	2 &lt;= m, n &lt;= 300
	4 &lt;= m * n &lt;= 2 * 104
	grid[i][j] is either 0, 1, or 2.
	grid[0][0] == grid[m - 1][n - 1] == 0


class Solution(object):
    def maximumMinutes(self, A):
        m, n = len(A), len(A[0])
        inf = 10 ** 10
        d = [[0,1],[1,0],[0,-1],[-1,0]]
        fires = [[i, j, 0] for i in range(m) for j in range(n) if A[i][j] == 1]
        A = [[inf if a < 2 else -1 for a in r] for r in A]

        def bfs(queue, seen):
            for i, j, t in queue:
                if seen[i][j] < inf: continue
                seen[i][j] = t
                for di,dj in d:
                    x, y = i + di, j + dj
                    if 0 <= x < m and 0 <= y < n and seen[x][y] >= inf and t + 1 < A[x][y]:
                        queue.append([x, y, t + 1])
        
        def die(t):
            seen = [[inf + 10] * n for i in range(m)]
            bfs([[0, 0, t]], seen)
            return seen[-1][-1] > A[-1][-1]

        bfs(fires, A)
        A[-1][-1] += 1
        return bisect_left(range(10**9 + 1), True, key=die) - 1
import java.util.Arrays;
import java.util.LinkedList;
import java.util.Queue;

class Solution {

    public boolean ok(int[][] grid, int[][] dist, int wait_time) {
        int n = grid.length;
        int m = grid[0].length;

        Queue<Pair<Integer, Integer, Integer>> Q = new LinkedList<>();
        Q.add(new Pair<>(0, 0, wait_time));

        int[][] visited = new int[n][m];
        visited[0][0] = 1;

        while (!Q.isEmpty()) {
            Pair<Integer, Integer, Integer> at = Q.poll();
            int[][] moves = new int[][]{{-1, 0}, {1, 0}, {0, -1}, {0, 1}};

            for (int[] to : moves) {
                int ii = at.first + to[0];
                int jj = at.second + to[1];
                if (!inBounds(ii, jj, n, m) || visited[ii][jj] == 1 || grid[ii][jj] == 2) continue;
                if (ii == n - 1 && jj == m - 1 && dist[ii][jj] >= at.third + 1) return true;
                if (dist[ii][jj] <= at.third + 1) continue;
                Q.add(new Pair<>(ii, jj, 1 + at.third));
                visited[ii][jj] = 1;
            }
        }
        return false;
    }

    public boolean inBounds(int i, int j, int n, int m) {
        return (0 <= i && i < n && 0 <= j && j < m);
    }

    public int maximumMinutes(int[][] grid) {
        int n = grid.length;
        int m = grid[0].length;

        int[][] dist = new int[n][m];

        for (int[] r : dist) Arrays.fill(r, Integer.MAX_VALUE);

        Queue<Pair<Integer, Integer, Integer>> Q = new LinkedList<>();

        for (int i = 0; i < n; i++) {
            for (int j = 0; j < m; j++) {
                if (grid[i][j] == 1) {
                    Q.add(new Pair<>(i, j, 0));
                    dist[i][j] = 0;
                }
            }
        }

        while (!Q.isEmpty()) {
            Pair<Integer, Integer, Integer> at = Q.poll();
            int[][] moves = new int[][]{{-1, 0}, {1, 0}, {0, -1}, {0, 1}};
            for (int[] to : moves) {
                int ii = at.first + to[0];
                int jj = at.second + to[1];
                if (!inBounds(ii, jj, n, m) || grid[ii][jj] == 2 || dist[ii][jj] <= at.third + 1) continue;
                dist[ii][jj] = 1 + at.third;
                Q.add(new Pair<>(ii, jj, 1 + at.third));
            }
        }

        int left = 0;
        int right = 1_000_000_000;

        int ans = -1;

        while (left <= right) {
            int mid = left + (right - left) / 2;
            if (ok(grid, dist, mid)) {
                ans = mid;
                left = mid + 1;
            } else right = mid - 1;
        }

        return ans;
    }

    static class Pair<T, K, L> {
        T first;
        K second;
        L third;

        public Pair(T first, K second, L third) {
            this.first = first;
            this.second = second;
            this.third = third;
        }
    }

}
class Solution {
public:
    int maximumMinutes(vector<vector<int>>& grid) {
        int m = grid.size();
        int n = grid[0].size();
        vector<vector<int>> firetime(m, vector<int>(n, INT_MAX));
        queue<pair<int, int>> q;
        // push fire positions into queue, and set the time as 0
        for(int i=0; i<m; i++){
            for(int j=0; j<n; j++){
                if(grid[i][j]==1){
                    q.push(make_pair(i, j));
                    firetime[i][j] = 0;
                }
            }
        }
        int time = 0;
        pair<int, int> xy;
        int x,y;
        // use BFS to find fire spread time
        while(!q.empty()){
            int points = q.size();
            time++;
            for(int i=0; i<points; i++){
                xy = q.front();
                q.pop();
                x = xy.first, y = xy.second;
                if(x-1>=0 && grid[x-1][y]==0 && firetime[x-1][y]==INT_MAX){
                    q.push(make_pair(x-1, y));
                    firetime[x-1][y] = time;
                }
                if(x+1<m && grid[x+1][y]==0 && firetime[x+1][y]==INT_MAX){
                    q.push(make_pair(x+1, y));
                    firetime[x+1][y] = time;
                }
                if(y-1>=0 && grid[x][y-1]==0 && firetime[x][y-1]==INT_MAX){
                    q.push(make_pair(x, y-1));
                    firetime[x][y-1] = time;
                }
                if(y+1<n && grid[x][y+1]==0 && firetime[x][y+1]==INT_MAX){
                    q.push(make_pair(x, y+1));
                    firetime[x][y+1] = time;
                }
            }
        }
        vector<vector<int>> peopletime(m, vector<int>(n, INT_MAX));
        time = 0;
        // push the initial position of the top left cell into the queue
        // and set the time as 0
        q.push(make_pair(0, 0));
        peopletime[0][0] = 0;
        // use BFS to find the traversal time
        while(!q.empty()){
            int points = q.size();
            time++;
            for(int i=0; i<points; i++){
                xy = q.front();
                q.pop();
                x = xy.first, y = xy.second;
                if(x-1>=0 && grid[x-1][y]==0 && peopletime[x-1][y]==INT_MAX && firetime[x-1][y]>time){
                    q.push(make_pair(x-1, y));
                    peopletime[x-1][y] = time;
                }
                if(x+1<m && grid[x+1][y]==0 && peopletime[x+1][y]==INT_MAX && firetime[x+1][y]>time){
                    q.push(make_pair(x+1, y));
                    peopletime[x+1][y] = time;
                }
                if(y-1>=0 && grid[x][y-1]==0 && peopletime[x][y-1]==INT_MAX && firetime[x][y-1]>time){
                    q.push(make_pair(x, y-1));
                    peopletime[x][y-1] = time;
                }
                if(y+1<n && grid[x][y+1]==0 && peopletime[x][y+1]==INT_MAX && firetime[x][y+1]>time){
                    q.push(make_pair(x, y+1));
                    peopletime[x][y+1] = time;
                }
                if(((x==m-2 && y==n-1) || (x==m-1 && y==n-2))&&(firetime[m-1][n-1]<=time)){
                    q.push(make_pair(m-1, n-1));
                    peopletime[m-1][n-1] = time;
                }
            }
        }
        // if you cannot reach the safehouse or fire reaches the safehouse first,
        // return -1
        if(peopletime[m-1][n-1]==INT_MAX || firetime[m-1][n-1]<peopletime[m-1][n-1]){
            return -1;
        }
        // if fire can never reach the safehouse,
        // return 1000000000
        if(firetime[m-1][n-1]==INT_MAX){
            return 1000000000;
        }
        if(firetime[m-1][n-1]==peopletime[m-1][n-1]){
            return 0;
        }
        int diff = (firetime[m-1][n-1]-peopletime[m-1][n-1]);
        if(m>1 && n>1){
            if(peopletime[m-2][n-1]!=INT_MAX && peopletime[m-1][n-2]!=INT_MAX && ((firetime[m-2][n-1]-peopletime[m-2][n-1])>diff || (firetime[m-1][n-2]-peopletime[m-1][n-2]>diff))){
                return diff;
            }
        }
        return diff-1;
    }
};
var maximumMinutes = function(grid) {
  let fireSpread = getFireSpreadTime(grid);
  let low = 0, high = 10 ** 9;
  while (low < high) {
    let mid = Math.ceil((low + high) / 2);
    if (canReachSafehouse(grid, fireSpread, mid)) low = mid;
    else high = mid - 1;
  }
  return canReachSafehouse(grid, fireSpread, low) ? low : -1;
};

function canReachSafehouse(originalGrid, fireSpread, timeToWait) {
  const directions = [[0, 1], [1, 0], [0, -1], [-1, 0]];
  let grid = originalGrid.map((row) => [...row]);
  let m = grid.length, n = grid[0].length;
  let queue = [[0, 0]], time = timeToWait;
  while (queue.length) {
    for (let i = queue.length; i > 0; i--) {
      let [row, col] = queue.shift();
      if (row === m - 1 && col === n - 1) {
        return true;
      }
      for (let [x, y] of directions) {
        let newX = row + x, newY = col + y;
        if (newX < 0 || newX >= m || newY < 0 || newY >= n || grid[newX][newY] !== 0) continue; // out of bounds or cell is not grass
        let isTarget = newX === m - 1 && newY === n - 1;
        if ((isTarget && time + 1 <= fireSpread[newX][newY]) || time + 1 < fireSpread[newX][newY]) { // only visit if fire will not spread to new cell at the next minute
          grid[newX][newY] = 1;
          queue.push([newX, newY]);
        }
      }
    }
    time++;
  }
  return false;
}

function getFireSpreadTime(originalGrid) {
  const directions = [[0, 1], [1, 0], [0, -1], [-1, 0]];
  let grid = originalGrid.map((row) => [...row]);
  let m = grid.length, n = grid[0].length;
  let queue = [];
  for (let i = 0; i < m; i++) {
    for (let j = 0; j < n; j++) {
      if (grid[i][j] === 1) {
        queue.push([i, j]);
      }
    }
  }
  
  let time = 0, fireSpread = Array(m).fill(0).map(() => Array(n).fill(Infinity));
  while (queue.length) {
    for (let i = queue.length; i > 0; i--) {
      let [row, col] = queue.shift();
      fireSpread[row][col] = time;
      for (let [x, y] of directions) {
        let newX = row + x, newY = col + y;
        if (newX < 0 || newX >= m || newY < 0 || newY >= n || grid[newX][newY] !== 0) continue; // out of bounds or cell is not grass
        grid[newX][newY] = 1;
        queue.push([newX, newY]);
      }
    }
    time++;
  }
  return fireSpread;
}
Escape the Spreading Fire