The Meeting Place Sequel - Amazon Top Interview Questions


Problem Statement :


You are given a two dimensional integer matrix consisting of:

0 which represents an empty cell.
1 which represents a wall.
2 which represents a person.
A person can walk up, down, left, right or stay in one time unit. Find a walkable cell such that it minimizes the time it would take for everyone to meet and return the time.

Note: two people can walk through the same empty cell and you can assume there is always some path between any two people.

Constraints

The number of cells in the matrix is at most 100,000

Any two people are at most 30 travel distance away

There are at most 30 people in the matrix

Example 1

Input

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

Output

3

Explanation

If we set the meeting place to matrix[2][1] then everyone can get there in at most 3 steps.



Solution :



title-img




                        Solution in C++ :

bool isSafe(vector<vector<int>> &matrix, int r, int c) {
    int m = matrix.size();
    int n = matrix[0].size();

    return (r >= 0 && c >= 0 && r < m && c < n && matrix[r][c] != 1);
}

void bfs(vector<vector<int>> &matrix, vector<vector<int>> &answer, int row, int col) {
    int m = matrix.size();
    int n = matrix[0].size();

    int hor[4] = {-1, 1, 0, 0};
    int ver[4] = {0, 0, 1, -1};

    vector<vector<bool>> visited(m, vector<bool>(n, false));
    queue<vector<int>> nodes;

    nodes.push({row, col, 0});
    visited[row][col] = true;

    while (!nodes.empty()) {
        int curRow = nodes.front()[0];
        int curCol = nodes.front()[1];
        int level = nodes.front()[2];
        nodes.pop();

        answer[curRow][curCol] = max(answer[curRow][curCol], level);

        for (int i = 0; i < 4; i++) {
            int newRow = curRow + hor[i];
            int newCol = curCol + ver[i];

            if (isSafe(matrix, newRow, newCol) && !visited[newRow][newCol]) {
                visited[newRow][newCol] = true;
                nodes.push({newRow, newCol, level + 1});
            }
        }
    }

    return;
}

int solve(vector<vector<int>> &matrix) {
    int m = matrix.size();
    int n = matrix[0].size();

    vector<vector<int>> answer(m, vector<int>(n, -1));

    for (int i = 0; i < m; i++) {
        for (int j = 0; j < n; j++) {
            if (matrix[i][j] == 1) answer[i][j] = 31;
        }
    }

    for (int i = 0; i < m; i++) {
        for (int j = 0; j < n; j++) {
            if (matrix[i][j] == 2) {
                bfs(matrix, answer, i, j);
            }
        }
    }

    int minTime = 31;
    for (int i = 0; i < m; i++) {
        for (int j = 0; j < n; j++) {
            if (answer[i][j] != -1) minTime = min(minTime, answer[i][j]);
        }
    }

    return (minTime == 31 ? 0 : minTime);
}
                    


                        Solution in Java :

import java.util.*;

class Solution {
    int dis[][][];
    public int solve(int[][] mat) {
        int res = Integer.MAX_VALUE;
        int n = mat.length, m = mat[0].length;
        List<int[]> list = new ArrayList<>();
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < m; j++) {
                if (mat[i][j] == 2) {
                    list.add(new int[] {i, j});
                }
            }
        }
        dis = new int[n][m][list.size()];
        for (int i = 0; i < dis.length; i++) {
            for (int j = 0; j < dis[0].length; j++) {
                Arrays.fill(dis[i][j], -1);
            }
        }

        for (int i = 0; i < list.size(); i++) {
            bfs(mat, list.get(i)[0], list.get(i)[1], i);
        }

        for (int i = 0; i < n; i++) {
            for (int j = 0; j < m; j++) {
                int sum = 0;
                for (int k = 0; k < dis[i][j].length; k++) {
                    if (dis[i][j][k] == -1) {
                        sum = Integer.MAX_VALUE;
                        break;
                    } else {
                        sum = Math.max(sum, dis[i][j][k]);
                    }
                }
                res = Math.min(res, sum);
            }
        }
        return res;
    }

    public void bfs(int mat[][], int sr, int sc, int index) {
        Queue<int[]> q = new LinkedList<>();
        q.add(new int[] {sr, sc, 0});
        dis[sr][sc][index] = 0;
        while (q.size() != 0) {
            int pair[] = q.poll();
            int r = pair[0], c = pair[1], level = pair[2];
            add(q, mat, r + 1, c, level + 1, index);
            add(q, mat, r - 1, c, level + 1, index);
            add(q, mat, r, c + 1, level + 1, index);
            add(q, mat, r, c - 1, level + 1, index);
        }
    }

    public void add(Queue<int[]> q, int mat[][], int i, int j, int level, int index) {
        if (i < 0 || j < 0 || i >= mat.length || j >= mat[0].length)
            return;
        if (mat[i][j] == 1)
            return;
        if (dis[i][j][index] != -1)
            return;
        dis[i][j][index] = level;
        q.add(new int[] {i, j, level});
    }
}
                    


                        Solution in Python : 
                            
class Solution:
    def solve(self, matrix):
        m, n = len(matrix), len(matrix[0])
        distGrid = [[float("inf") for _ in range(n)] for _ in range(m)]

        def bfs(i, j):
            queue = deque([(i, j, 0)])
            visited = [[False for _ in range(n)] for _ in range(m)]
            visited[i][j] = True
            while queue:
                x, y, dist = queue.popleft()
                if distGrid[x][y] == float("inf"):
                    distGrid[x][y] = 0
                distGrid[x][y] = max(distGrid[x][y], dist)
                for r, c in [(x + 1, y), (x - 1, y), (x, y + 1), (x, y - 1)]:
                    if 0 <= r < m and 0 <= c < n and not visited[r][c] and matrix[r][c] != 1:
                        visited[r][c] = True
                        queue.append((r, c, dist + 1))

        for i in range(m):
            for j in range(n):
                if matrix[i][j] == 2:
                    bfs(i, j)

        res = min(min(row) for row in distGrid)
        return res if res != float("inf") else 0
                    


View More Similar Problems

Queries with Fixed Length

Consider an -integer sequence, . We perform a query on by using an integer, , to calculate the result of the following expression: In other words, if we let , then you need to calculate . Given and queries, return a list of answers to each query. Example The first query uses all of the subarrays of length : . The maxima of the subarrays are . The minimum of these is . The secon

View Solution →

QHEAP1

This question is designed to help you get a better understanding of basic heap operations. You will be given queries of types: " 1 v " - Add an element to the heap. " 2 v " - Delete the element from the heap. "3" - Print the minimum of all the elements in the heap. NOTE: It is guaranteed that the element to be deleted will be there in the heap. Also, at any instant, only distinct element

View Solution →

Jesse and Cookies

Jesse loves cookies. He wants the sweetness of all his cookies to be greater than value K. To do this, Jesse repeatedly mixes two cookies with the least sweetness. He creates a special combined cookie with: sweetness Least sweet cookie 2nd least sweet cookie). He repeats this procedure until all the cookies in his collection have a sweetness > = K. You are given Jesse's cookies. Print t

View Solution →

Find the Running Median

The median of a set of integers is the midpoint value of the data set for which an equal number of integers are less than and greater than the value. To find the median, you must first sort your set of integers in non-decreasing order, then: If your set contains an odd number of elements, the median is the middle element of the sorted sample. In the sorted set { 1, 2, 3 } , 2 is the median.

View Solution →

Minimum Average Waiting Time

Tieu owns a pizza restaurant and he manages it in his own way. While in a normal restaurant, a customer is served by following the first-come, first-served rule, Tieu simply minimizes the average waiting time of his customers. So he gets to decide who is served first, regardless of how sooner or later a person comes. Different kinds of pizzas take different amounts of time to cook. Also, once h

View Solution →

Merging Communities

People connect with each other in a social network. A connection between Person I and Person J is represented as . When two persons belonging to different communities connect, the net effect is the merger of both communities which I and J belongs to. At the beginning, there are N people representing N communities. Suppose person 1 and 2 connected and later 2 and 3 connected, then ,1 , 2 and 3 w

View Solution →