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

Insert a Node at the Tail of a Linked List

You are given the pointer to the head node of a linked list and an integer to add to the list. Create a new node with the given integer. Insert this node at the tail of the linked list and return the head node of the linked list formed after inserting this new node. The given head pointer may be null, meaning that the initial list is empty. Input Format: You have to complete the SinglyLink

View Solution →

Insert a Node at the head of a Linked List

Given a pointer to the head of a linked list, insert a new node before the head. The next value in the new node should point to head and the data value should be replaced with a given value. Return a reference to the new head of the list. The head pointer given may be null meaning that the initial list is empty. Function Description: Complete the function insertNodeAtHead in the editor below

View Solution →

Insert a node at a specific position in a linked list

Given the pointer to the head node of a linked list and an integer to insert at a certain position, create a new node with the given integer as its data attribute, insert this node at the desired position and return the head node. A position of 0 indicates head, a position of 1 indicates one node away from the head and so on. The head pointer given may be null meaning that the initial list is e

View Solution →

Delete a Node

Delete the node at a given position in a linked list and return a reference to the head node. The head is at position 0. The list may be empty after you delete the node. In that case, return a null value. Example: list=0->1->2->3 position=2 After removing the node at position 2, list'= 0->1->-3. Function Description: Complete the deleteNode function in the editor below. deleteNo

View Solution →

Print in Reverse

Given a pointer to the head of a singly-linked list, print each data value from the reversed list. If the given list is empty, do not print anything. Example head* refers to the linked list with data values 1->2->3->Null Print the following: 3 2 1 Function Description: Complete the reversePrint function in the editor below. reversePrint has the following parameters: Sing

View Solution →

Reverse a linked list

Given the pointer to the head node of a linked list, change the next pointers of the nodes so that their order is reversed. The head pointer given may be null meaning that the initial list is empty. Example: head references the list 1->2->3->Null. Manipulate the next pointers of each node in place and return head, now referencing the head of the list 3->2->1->Null. Function Descriptio

View Solution →