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

Left Rotation

A left rotation operation on an array of size n shifts each of the array's elements 1 unit to the left. Given an integer, d, rotate the array that many steps left and return the result. Example: d=2 arr=[1,2,3,4,5] After 2 rotations, arr'=[3,4,5,1,2]. Function Description: Complete the rotateLeft function in the editor below. rotateLeft has the following parameters: 1. int d

View Solution →

Sparse Arrays

There is a collection of input strings and a collection of query strings. For each query string, determine how many times it occurs in the list of input strings. Return an array of the results. Example: strings=['ab', 'ab', 'abc'] queries=['ab', 'abc', 'bc'] There are instances of 'ab', 1 of 'abc' and 0 of 'bc'. For each query, add an element to the return array, results=[2,1,0]. Fun

View Solution →

Array Manipulation

Starting with a 1-indexed array of zeros and a list of operations, for each operation add a value to each of the array element between two given indices, inclusive. Once all operations have been performed, return the maximum value in the array. Example: n=10 queries=[[1,5,3], [4,8,7], [6,9,1]] Queries are interpreted as follows: a b k 1 5 3 4 8 7 6 9 1 Add the valu

View Solution →

Print the Elements of a Linked List

This is an to practice traversing a linked list. Given a pointer to the head node of a linked list, print each node's data element, one per line. If the head pointer is null (indicating the list is empty), there is nothing to print. Function Description: Complete the printLinkedList function in the editor below. printLinkedList has the following parameter(s): 1.SinglyLinkedListNode

View Solution →

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 →