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 :
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
Tree Coordinates
We consider metric space to be a pair, , where is a set and such that the following conditions hold: where is the distance between points and . Let's define the product of two metric spaces, , to be such that: , where , . So, it follows logically that is also a metric space. We then define squared metric space, , to be the product of a metric space multiplied with itself: . For
View Solution →Array Pairs
Consider an array of n integers, A = [ a1, a2, . . . . an] . Find and print the total number of (i , j) pairs such that ai * aj <= max(ai, ai+1, . . . aj) where i < j. Input Format The first line contains an integer, n , denoting the number of elements in the array. The second line consists of n space-separated integers describing the respective values of a1, a2 , . . . an .
View Solution →Self Balancing Tree
An AVL tree (Georgy Adelson-Velsky and Landis' tree, named after the inventors) is a self-balancing binary search tree. In an AVL tree, the heights of the two child subtrees of any node differ by at most one; if at any time they differ by more than one, rebalancing is done to restore this property. We define balance factor for each node as : balanceFactor = height(left subtree) - height(righ
View Solution →Array and simple queries
Given two numbers N and M. N indicates the number of elements in the array A[](1-indexed) and M indicates number of queries. You need to perform two types of queries on the array A[] . You are given queries. Queries can be of two types, type 1 and type 2. Type 1 queries are represented as 1 i j : Modify the given array by removing elements from i to j and adding them to the front. Ty
View Solution →Median Updates
The median M of numbers is defined as the middle number after sorting them in order if M is odd. Or it is the average of the middle two numbers if M is even. You start with an empty number list. Then, you can add numbers to the list, or remove existing numbers from it. After each add or remove operation, output the median. Input: The first line is an integer, N , that indicates the number o
View Solution →Maximum Element
You have an empty sequence, and you will be given N queries. Each query is one of these three types: 1 x -Push the element x into the stack. 2 -Delete the element present at the top of the stack. 3 -Print the maximum element in the stack. Input Format The first line of input contains an integer, N . The next N lines each contain an above mentioned query. (It is guaranteed that each
View Solution →