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

<ul>
	<li><code>0</code> represents grass,</li>
	<li><code>1</code> represents fire,</li>
	<li><code>2</code> represents a wall that you and fire cannot pass through.</li>
</ul>

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

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

<p>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.</p>

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

<p>&nbsp;</p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://assets.leetcode.com/uploads/2022/03/10/ex1new.jpg" style="width: 650px; height: 404px;" />
<pre>
<strong>Input:</strong> 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]]
<strong>Output:</strong> 3
<strong>Explanation:</strong> 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.</pre>

<p><strong class="example">Example 2:</strong></p>
<img alt="" src="https://assets.leetcode.com/uploads/2022/03/10/ex2new2.jpg" style="width: 515px; height: 150px;" />
<pre>
<strong>Input:</strong> grid = [[0,0,0,0],[0,1,2,0],[0,2,0,0]]
<strong>Output:</strong> -1
<strong>Explanation:</strong> 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.
</pre>

<p><strong class="example">Example 3:</strong></p>
<img alt="" src="https://assets.leetcode.com/uploads/2022/03/10/ex3new.jpg" style="width: 174px; height: 150px;" />
<pre>
<strong>Input:</strong> grid = [[0,0,0],[2,2,0],[1,2,0]]
<strong>Output:</strong> 1000000000
<strong>Explanation:</strong> 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, 10<sup>9</sup> is returned.
</pre>

<p>&nbsp;</p>
<p><strong>Constraints:</strong></p>

<ul>
	<li><code>m == grid.length</code></li>
	<li><code>n == grid[i].length</code></li>
	<li><code>2 &lt;= m, n &lt;= 300</code></li>
	<li><code>4 &lt;= m * n &lt;= 2 * 10<sup>4</sup></code></li>
	<li><code>grid[i][j]</code> is either <code>0</code>, <code>1</code>, or <code>2</code>.</li>
	<li><code>grid[0][0] == grid[m - 1][n - 1] == 0</code></li>
</ul>

class Solution:
    def maximumMinutes(self, grid: List[List[int]]) -> int:
        max_mins = 1_000_000_000
        def mbfs(adj, *s):
            lvls = {}
            parents = {}

            # queue
            frontier = []
            i = 1
            for start in s:
                lvls[start] = 0
                parents[start] = None
                frontier.append(start)
            
            while frontier:
                next = []
                
                for u in frontier:
                    r, c = u
                    # search in all directions
                    for dr, dc in [(1,0), (-1,0), (0, 1), (0,-1)]:
                        new_row = r + dr
                        new_col = c + dc
                        v = (new_row, new_col)
                        if new_row>=0 and new_row<len(adj) and new_col>=0 and new_col<len(adj[0]):
                            if adj[new_row][new_col] != 2 and v not in lvls:
                                lvls[v] = i
                                parents[v] = u
                                next.append(v)
                frontier = next
                i+=1
            return {'lvls': lvls, 'parents': parents}

        def check_path(mins, adj, pmoves, fmoves):
            end_pos = (len(adj)-1, len(adj[0])-1)
            parent_cell = pmoves['parents'].get(end_pos)
            min_to_cell = pmoves['lvls'].get(parent_cell, -1)
            delta_min = mins + min_to_cell

            if not parent_cell:
                return False

            if fmoves['lvls'].get((0,0)) == 1:
                if pmoves['lvls'].get(1,0):
                    if pmoves['lvls'].get((1,0)) == fmoves['lvls'].get((1,0)):
                        return False
                elif pmoves['lvls'].get(0,1):
                    if pmoves['lvls'].get((0,1)) == fmoves['lvls'].get((0,1)):
                        return False

            if fmoves['lvls'].get(end_pos) == pmoves['lvls'].get(end_pos):
                if mins > 0:
                    return False
            
            if fmoves['lvls'].get(end_pos)-mins < pmoves['lvls'].get(end_pos):
                return False

            b_parent = pmoves['parents'].get((len(adj)-2, len(adj[0])-1))
            while delta_min >= 0:
                fire_lvl = fmoves['lvls'].get(parent_cell)
                alt_fire_lvl = fmoves['lvls'].get(b_parent)
                person_lvl = pmoves['lvls'].get(parent_cell, 0)

                if fire_lvl:

                    if alt_fire_lvl and alt_fire_lvl >= delta_min:
                        pass
                    elif fire_lvl <= delta_min:
                        return False
            
                parent_cell = pmoves['parents'].get(parent_cell)
                delta_min-=1
            return True

        fires = []
        for r in range(len(grid)):
            for c in range(len(grid[0])):
                cell = grid[r][c]
                if cell == 1:
                    fires.append((r,c))

        fire_moves = mbfs(grid, *fires)
        person_moves = mbfs(grid, (0, 0))

        fmoves_to_exit = fire_moves['lvls'].get((len(grid)-1, len(grid[0])-1))
        pmoves_to_exit = person_moves['lvls'].get((len(grid)-1, len(grid[0])-1))

        if not pmoves_to_exit:
            return -1

        if not fmoves_to_exit:
            return max_mins

        if fmoves_to_exit < pmoves_to_exit:
            return -1
        
        if len(fire_moves['lvls']) == len(fires):
            return max_mins

        left = 0
        right = fmoves_to_exit
        current_max = -1
        while left <= right:
            mid = left + (right - left) // 2
            if check_path(mid, grid, person_moves, fire_moves):
                left = mid + 1
                current_max = mid
            else:
                right = mid - 1
        
        return current_max

21400