Wildfire Sequel- Amazon Top Interview Questions


Problem Statement :


You are given a two-dimensional integer matrix matrix where

0 represents empty cell
1 represents a person
2 represents fire
3 represents a wall
You can assume there's only one person and in each turn fire expands in all four directions although fire can't expand through walls.

Return whether the person can move to either the top left corner or the bottom right corner. In each turn, the person moves first, then the fire expands. If the person makes it to either square as the same time as the fire, then they're safe.

Note that if you go a the square and then the fire expands in the same turn to the same square, you still survive.

Constraints

1 ≤ n, m < 250 where n and m are the number of rows and columns in matrix

Example 1

Input

matrix = [
    [0, 0, 0],
    [0, 1, 0],
    [0, 2, 0]
]

Output

True

Explanation

The person can get to the top left corner.

Example 2

Input

matrix = [
    [0, 2, 0],
    [0, 1, 0],
    [0, 2, 0]
]

Output

False

Explanation

There's fire getting in the way of the top left and bottom right corners.



Solution :



title-img




                        Solution in C++ :

bool solve(vector<vector<int>>& matrix) {
    int a, b, x, y, e, n = matrix.size(), m = matrix[0].size();

    queue<pair<pair<int, int>, int>> bfs;
    vector<int> dir{1, 0, -1, 0, 1};

    for (int i = 0; i < matrix.size(); i++) {
        for (int j = 0; j < matrix[0].size(); j++) {
            if (matrix[i][j] == 1) {
                bfs.push({{i, j}, matrix[i][j]});
            }
        }
    }

    for (int i = 0; i < matrix.size(); i++) {
        for (int j = 0; j < matrix[0].size(); j++) {
            if (matrix[i][j] == 2) {
                bfs.push({{i, j}, matrix[i][j]});
            }
        }
    }

    while (!bfs.empty()) {
        int s = bfs.size();

        for (int i = 0; i < s; i++) {
            a = bfs.front().first.first;
            b = bfs.front().first.second;
            e = bfs.front().second;

            if (a == 0 && b == 0 && e == 1) {
                return true;
            }
            if (a == n - 1 && b == m - 1 && e == 1) {
                return true;
            }

            for (int j = 0; j < 4; j++) {
                x = a + dir[j];
                y = b + dir[j + 1];

                if (x < 0 || y < 0 || x == matrix.size() || y == matrix[0].size()) {
                    continue;
                }
                if (matrix[x][y] == 3 || matrix[x][y] == 2) {
                    continue;
                }

                if (e == 1) {
                    if (matrix[x][y] == -1) {
                        continue;
                    }
                    if (x == 0 && y == 0 && matrix[i][j] != 2) {
                        return true;
                    }
                    if (x == n - 1 && y == m - 1 && matrix[i][j] != 2) {
                        return true;
                    }
                    matrix[x][y] = -1;
                    bfs.push({{x, y}, 1});
                }
                if (e == 2) {
                    matrix[x][y] = 2;
                    bfs.push({{x, y}, 2});
                }
            }

            bfs.pop();
        }
    }

    return false;
}
                    


                        Solution in Java :

import java.util.*;

class Solution {
    static int N;
    static int M;
    static int[][] matrix;
    static int[][] fire;
    static int[][] escape;
    public boolean solve(int[][] m) {
        matrix = m;
        N = matrix.length;
        M = matrix[0].length;
        fire = floodfill(2);
        escape = floodfill(1);
        return (works(0, 0) || works(N - 1, M - 1));
    }

    public static boolean works(int r, int c) {
        return (escape[r][c] < Integer.MAX_VALUE && escape[r][c] <= fire[r][c]);
    }

    public static int[][] floodfill(int root) {
        int[][] time = new int[N][M];
        for (int i = 0; i < N; i++) Arrays.fill(time[i], Integer.MAX_VALUE);
        ArrayDeque<int[]> bfs = new ArrayDeque<int[]>();
        for (int i = 0; i < N; i++) {
            for (int j = 0; j < M; j++) {
                if (matrix[i][j] == root) {
                    time[i][j] = 0;
                    bfs.add(new int[] {i, j});
                }
            }
        }
        int[][] dirs = {{-1, 0}, {1, 0}, {0, 1}, {0, -1}};
        while (!bfs.isEmpty()) {
            int[] cell = bfs.pollFirst();
            for (int[] dir : dirs) {
                int newR = cell[0] + dir[0];
                int newC = cell[1] + dir[1];
                if (newR >= 0 && newC >= 0 && newR < N && newC < M && matrix[newR][newC] != 3
                    && time[newR][newC] == Integer.MAX_VALUE) {
                    time[newR][newC] = time[cell[0]][cell[1]] + 1;
                    bfs.add(new int[] {newR, newC});
                }
            }
        }
        return time;
    }
}
                    


                        Solution in Python : 
                            
class Solution:
    def solve(self, A):
        INF = int(1e9)
        R, C = len(A), len(A[0])

        def neighbors(r, c):
            for nr, nc in [[r - 1, c], [r, c - 1], [r + 1, c], [r, c + 1]]:
                if 0 <= nr < R and 0 <= nc < C and A[nr][nc] != 3:
                    yield nr, nc

        def bfs(queue) -> dict:
            dist = {node: 0 for node in queue}
            while queue:
                node = queue.popleft()
                for nei in neighbors(*node):
                    if nei not in dist:
                        dist[nei] = dist[node] + 1
                        queue.append(nei)
            return dist

        qfire = collections.deque()
        qperson = collections.deque()
        for r, row in enumerate(A):
            for c, v in enumerate(row):
                if v == 1:
                    qperson.append((r, c))
                elif v == 2:
                    qfire.append((r, c))

        dist_fire = bfs(qfire)
        dist_person = bfs(qperson)
        for place in ((0, 0), (R - 1, C - 1)):
            if dist_fire.get(place, INF) >= dist_person.get(place, 2 * INF):
                return True
        return False
                    


View More Similar Problems

Palindromic Subsets

Consider a lowercase English alphabetic letter character denoted by c. A shift operation on some c turns it into the next letter in the alphabet. For example, and ,shift(a) = b , shift(e) = f, shift(z) = a . Given a zero-indexed string, s, of n lowercase letters, perform q queries on s where each query takes one of the following two forms: 1 i j t: All letters in the inclusive range from i t

View Solution →

Counting On a Tree

Taylor loves trees, and this new challenge has him stumped! Consider a tree, t, consisting of n nodes. Each node is numbered from 1 to n, and each node i has an integer, ci, attached to it. A query on tree t takes the form w x y z. To process a query, you must print the count of ordered pairs of integers ( i , j ) such that the following four conditions are all satisfied: the path from n

View Solution →

Polynomial Division

Consider a sequence, c0, c1, . . . , cn-1 , and a polynomial of degree 1 defined as Q(x ) = a * x + b. You must perform q queries on the sequence, where each query is one of the following two types: 1 i x: Replace ci with x. 2 l r: Consider the polynomial and determine whether is divisible by over the field , where . In other words, check if there exists a polynomial with integer coefficie

View Solution →

Costly Intervals

Given an array, your goal is to find, for each element, the largest subarray containing it whose cost is at least k. Specifically, let A = [A1, A2, . . . , An ] be an array of length n, and let be the subarray from index l to index r. Also, Let MAX( l, r ) be the largest number in Al. . . r. Let MIN( l, r ) be the smallest number in Al . . .r . Let OR( l , r ) be the bitwise OR of the

View Solution →

The Strange Function

One of the most important skills a programmer needs to learn early on is the ability to pose a problem in an abstract way. This skill is important not just for researchers but also in applied fields like software engineering and web development. You are able to solve most of a problem, except for one last subproblem, which you have posed in an abstract way as follows: Given an array consisting

View Solution →

Self-Driving Bus

Treeland is a country with n cities and n - 1 roads. There is exactly one path between any two cities. The ruler of Treeland wants to implement a self-driving bus system and asks tree-loving Alex to plan the bus routes. Alex decides that each route must contain a subset of connected cities; a subset of cities is connected if the following two conditions are true: There is a path between ever

View Solution →