Physical Address

304 North Cardinal St.
Dorchester Center, MA 02124

Escape the Spreading Fire LeetCode Solution

Problem – Escape the Spreading Fire LeetCode Solution

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

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.

Constraints:

  • m == grid.length
  • n == grid[i].length
  • 2 <= m, n <= 300
  • 4 <= m * n <= 2 * 104
  • grid[i][j] is either 01, or 2.
  • grid[0][0] == grid[m - 1][n - 1] == 0

Escape the Spreading Fire LeetCode Solution in Python

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

Escape the Spreading Fire LeetCode Solution in Java

int[][] directions = new int[][]{{0,1},{0,-1},{1,0},{-1,0}};

public int maximumMinutes(int[][] grid) {
    int m = grid.length, n = grid[0].length;
    List<int[]> fires = new ArrayList<>();

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

    int l = -1, r = m * n;
    while (l < r) {
        int mid = l + (r - l) / 2 + 1;
        if (reachable(grid, mid, fires)) l = mid;
        else r = mid - 1;
    }
    return l == m * n ? (int) 1e9 : l;
}

boolean reachable(int[][] grid, int move, List<int[]> fires) {
    int m = grid.length, n = grid[0].length;
    int[][] copy = clone(grid);

    Queue<int[]> fire = new LinkedList<>();
    fire.addAll(fires);
    while (!fire.isEmpty() && move-- > 0) {
        if (spread(fire, copy)) return false;
    }

    Queue<int[]> person = new LinkedList<>();
    person.add(new int[]{0, 0});
    while (!person.isEmpty()) {
        boolean onFire = spread(fire, copy);
        if (spread(person, copy)) return true;
        if (onFire) return false;
    }
    return false;
}

// return true if it spreads to safehouse
boolean spread(Queue<int[]> queue, int[][] grid) {
    int m = grid.length, n = grid[0].length;
    int size = queue.size();

    while (size-- > 0) {
        int[] cell = queue.remove();
        for (int[] d : directions) {
            int x = cell[0] + d[0] , y = cell[1] + d[1];
            if (x == m - 1 && y == n - 1) return true;
            if (x >= 0 && x < m && y >= 0 && y < n && grid[x][y] == 0) {
                grid[x][y] = -1;
                queue.add(new int[]{x, y});
            }
        }
    }
    return false;
}

int[][] clone(int[][] grid) {
    int m = grid.length, n = grid[0].length;
    int[][] copy = new int[m][n];
    for (int i = 0; i < m; i++) {
        for (int j = 0; j < n; j++) {
            copy[i][j] = grid[i][j];
        }
    }
    return copy;
}

Escape the Spreading Fire LeetCode Solution in C++

int maximumMinutes(vector<vector<int>>& g) {
    int m = g.size(), n = g[0].size();
    deque<pair<int, int>> fire, person({{0, 0}});
    for (int i = 0; i < m; ++i)
        for (int j = 0; j < n; ++j)
            if (g[i][j] == 1) 
                fire.push_back({i, j});
    auto steps = [&](deque<pair<int, int>> &pos) {
        vector<vector<int>> st(m, vector<int>(n));
        while(!pos.empty()) {
            auto [i, j] = pos.front();
            pos.pop_front();
            for (auto [di, dj] : vector<pair<int, int>>{{0, 1}, {1, 0}, {0, -1}, {-1, 0}}) {
                int x = i + di, y = j + dj;
                if (min(x, y) >= 0 && x < m && y < n && g[x][y] == 0 && st[x][y] == 0) {
                    st[x][y] = st[i][j] + 1;
                    pos.push_back({x, y});
                }
            }
        }
        return array<int, 3>{st[m - 1][n - 1], st[m - 2][n - 1], st[m - 1][n - 2]};
    };
    auto f = steps(fire), p = steps(person);
    if (f[0] == 0 && p[0] != 0)
        return 1000000000;
    if (int diff = f[0] - p[0]; p[0] != 0 && diff >= 0)
        return diff - (f[1] - p[1] <= diff && f[2] - p[2] <= diff);
    return -1;
}
Escape the Spreading Fire LeetCode Solution Review:

In our experience, we suggest you solve this Escape the Spreading Fire LeetCode Solution and gain some new skills from Professionals completely free and we assure you will be worth it.

If you are stuck anywhere between any coding problem, just visit Queslers to get the Escape the Spreading Fire LeetCode Solution

Find on LeetCode

Conclusion:

I hope this Escape the Spreading Fire LeetCode Solution would be useful for you to learn something new from this problem. If it helped you then don’t forget to bookmark our site for more Coding Solutions.

This Problem is intended for audiences of all experiences who are interested in learning about Data Science in a business context; there are no prerequisites.

Keep Learning!

More Coding Solutions >>

LeetCode Solutions

Hacker Rank Solutions

CodeChef Solutions

Leave a Reply

Your email address will not be published. Required fields are marked *