Pick Up Gold in Two Locations - Amazon Top Interview Questions


Problem Statement :


You are given a two-dimensional list of integers matrix and integers row, col, erow0, ecol0, erow1, and ecol1. You are currently at matrix[row][col] and want to pick up gold that is at matrix[erow0][ecol0] and matrix[erow1][ecol1].

You can move up, down, left, and right but when you are at a cell (r, c), you incur cost matrix[r][c], although if you land at a cell more than once, you don't incur that cost again. Return the minimum cost to pick up gold at both locations.

Constraints

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

Example 1

Input

matrix = [
    [1, 1, 1, 1],
    [1, 9, 9, 9],
    [1, 1, 1, 9]
]

row = 0

col = 0

erow0 = 0

ecol0 = 3

erow1 = 2

ecol1 = 2

Output

8

Explanation

We're currently at (0, 0) and want to pick up gold at both (0, 3) and (2, 2).


First we move from (0, 0) to (0, 3) by moving right 3 steps. Then we come back to (0, 0). And then 
follow the 1s to (2, 2).


Example 2

Input

matrix = [
    [1, 1, 1]
]

row = 0

col = 0

erow0 = 0

ecol0 = 1

erow1 = 0

ecol1 = 2

Output

3

Explanation

We go right 2 steps. Note that we still incur the cost at the starting square.



Solution :



title-img




                        Solution in C++ :

int r, c;
int dx[4]{-1, 0, 1, 0};
int dy[4]{0, 1, 0, -1};
void dijkstra(vector<vector<int>>& dp, vector<vector<int>>& g, int sx, int sy) {
    dp[sx][sy] = g[sx][sy];
    priority_queue<pair<int, pair<int, int>>> q;
    q.emplace(-dp[sx][sy], make_pair(sx, sy));
    while (q.size()) {
        tie(sx, sy) = q.top().second;
        if (dp[sx][sy] != -q.top().first) {
            q.pop();
            continue;
        }
        q.pop();
        for (int k = 0; k < 4; k++) {
            int nx = sx + dx[k];
            int ny = sy + dy[k];
            if (nx < 0 || nx >= r || ny < 0 || ny >= c) {
                continue;
            }
            if (dp[nx][ny] > g[nx][ny] + dp[sx][sy]) {
                dp[nx][ny] = g[nx][ny] + dp[sx][sy];
                q.emplace(-dp[nx][ny], make_pair(nx, ny));
            }
        }
    }
}

void init(vector<vector<int>>& dp) {
    for (int i = 0; i < r; i++) {
        vector<int> v(c);
        fill(v.begin(), v.end(), 1e9);
        dp.push_back(v);
    }
}

int solve(vector<vector<int>>& matrix, int row, int col, int erow0, int ecol0, int erow1,
          int ecol1) {
    r = matrix.size();
    c = matrix[0].size();
    vector<vector<int>> adp, bdp, cdp;
    init(adp);
    init(bdp);
    init(cdp);
    long long ret = 1e18;
    dijkstra(adp, matrix, row, col);
    dijkstra(bdp, matrix, erow0, ecol0);
    dijkstra(cdp, matrix, erow1, ecol1);
    for (int i = 0; i < r; i++) {
        for (int j = 0; j < c; j++) {
            ret = min(ret, adp[i][j] + bdp[i][j] + cdp[i][j] - 2LL * matrix[i][j]);
        }
    }
    return ret;
}
                    


                        Solution in Java :

import java.util.*;

class Solution {
    public int solve(int[][] matrix, int row, int col, int erow0, int ecol0, int erow1, int ecol1) {
        // Run dijkstra's algorithm from each end point
        int[][] d1 = dijkstra(matrix, row, col);
        int[][] d2 = dijkstra(matrix, erow0, ecol0);
        int[][] d3 = dijkstra(matrix, erow1, ecol1);
        int ans = Integer.MAX_VALUE;
        int N = matrix.length;
        int M = matrix[0].length;
        for (int i = 0; i < N; i++) {
            for (int j = 0; j < M; j++) {
                // cell (i,j) is the "meeting point" of the 3 paths
                int cost = d1[i][j] + d2[i][j] + d3[i][j] - 2 * matrix[i][j];
                ans = Math.min(ans, cost);
            }
        }
        return ans;
    }

    public int[][] dijkstra(int[][] m, int row, int col) {
        int N = m.length;
        int M = m[0].length;
        int[][] dist = new int[N][M];
        for (int i = 0; i < N; i++) {
            Arrays.fill(dist[i], Integer.MAX_VALUE);
        }
        dist[row][col] = m[row][col];
        PriorityQueue<int[]> pq = new PriorityQueue<int[]>(new Comparator<int[]>() {
            @Override
            public int compare(int[] arr1, int[] arr2) {
                return arr1[2] - arr2[2];
            }
        });
        int[][] dirs = {{-1, 0}, {1, 0}, {0, 1}, {0, -1}};
        pq.add(new int[] {row, col, dist[row][col]});
        while (!pq.isEmpty()) {
            int[] cell = pq.poll();
            for (int[] dir : dirs) {
                int newR = cell[0] + dir[0];
                int newC = cell[1] + dir[1];
                if (newR < 0 || newR >= N || newC < 0 || newC >= M)
                    continue;
                int d = dist[cell[0]][cell[1]];
                if (dist[newR][newC] > d + m[newR][newC]) {
                    dist[newR][newC] = d + m[newR][newC];
                    pq.add(new int[] {newR, newC, dist[newR][newC]});
                }
            }
        }
        return dist;
    }
}
                    


                        Solution in Python : 
                            
class Solution:
    def solve(self, matrix, row, col, erow0, ecol0, erow1, ecol1):
        def is_valid(x, y):
            return x >= 0 and y >= 0 and x < len(matrix) and y < len(matrix[0])

        def min_cost(sx, sy):
            heap = [(matrix[sx][sy], sx, sy)]
            dists = [[math.inf] * len(matrix[0]) for _ in range(len(matrix))]
            dists[sx][sy] = matrix[sx][sy]
            while heap:
                cost, x, y = heapq.heappop(heap)
                for nx, ny in [(x, y - 1), (x + 1, y), (x - 1, y), (x, y + 1)]:
                    if is_valid(nx, ny) and matrix[nx][ny] + cost < dists[nx][ny]:
                        edge = matrix[nx][ny]
                        dists[nx][ny] = edge + cost
                        heapq.heappush(heap, (edge + cost, nx, ny))
            return dists

        res = math.inf
        a, b, c = min_cost(row, col), min_cost(erow0, ecol0), min_cost(erow1, ecol1)
        for i in range(len(matrix)):
            for j in range(len(matrix[0])):
                res = min(res, a[i][j] + b[i][j] + c[i][j] - 2 * matrix[i][j])
        return res
                    


View More Similar Problems

Balanced Brackets

A bracket is considered to be any one of the following characters: (, ), {, }, [, or ]. Two brackets are considered to be a matched pair if the an opening bracket (i.e., (, [, or {) occurs to the left of a closing bracket (i.e., ), ], or }) of the exact same type. There are three types of matched pairs of brackets: [], {}, and (). A matching pair of brackets is not balanced if the set of bra

View Solution →

Equal Stacks

ou have three stacks of cylinders where each cylinder has the same diameter, but they may vary in height. You can change the height of a stack by removing and discarding its topmost cylinder any number of times. Find the maximum possible height of the stacks such that all of the stacks are exactly the same height. This means you must remove zero or more cylinders from the top of zero or more of

View Solution →

Game of Two Stacks

Alexa has two stacks of non-negative integers, stack A = [a0, a1, . . . , an-1 ] and stack B = [b0, b1, . . . , b m-1] where index 0 denotes the top of the stack. Alexa challenges Nick to play the following game: In each move, Nick can remove one integer from the top of either stack A or stack B. Nick keeps a running sum of the integers he removes from the two stacks. Nick is disqualified f

View Solution →

Largest Rectangle

Skyline Real Estate Developers is planning to demolish a number of old, unoccupied buildings and construct a shopping mall in their place. Your task is to find the largest solid area in which the mall can be constructed. There are a number of buildings in a certain two-dimensional landscape. Each building has a height, given by . If you join adjacent buildings, they will form a solid rectangle

View Solution →

Simple Text Editor

In this challenge, you must implement a simple text editor. Initially, your editor contains an empty string, S. You must perform Q operations of the following 4 types: 1. append(W) - Append W string to the end of S. 2 . delete( k ) - Delete the last k characters of S. 3 .print( k ) - Print the kth character of S. 4 . undo( ) - Undo the last (not previously undone) operation of type 1 or 2,

View Solution →

Poisonous Plants

There are a number of plants in a garden. Each of the plants has been treated with some amount of pesticide. After each day, if any plant has more pesticide than the plant on its left, being weaker than the left one, it dies. You are given the initial values of the pesticide in each of the plants. Determine the number of days after which no plant dies, i.e. the time after which there is no plan

View Solution →