Shortest Absolute Value Distance - Google Top Interview Questions


Problem Statement :


You are given a two-dimensional list of integers matrix. 

You can move up, left, right, down and each move from matrix[a][b] to matrix[c][d] costs abs(matrix[a][b] - matrix[c][d]).

Return the minimum cost to move from the top left corner to the bottom right corner.

Constraints

1 ≤ n * m ≤ 200,000 where n and m are the number of rows and columns in matrix

Example 1

Input

matrix = [


    [1, 100, 1],

    [2, 5, 3],

    [1, 2, 3]

]

Output

4

Explanation

We can move from 1 -> 2 -> 1 -> 2 -> 3.



Solution :



title-img




                        Solution in C++ :

int solve(vector<vector<int>>& mat) {
    int n = mat.size(), m = mat[0].size();
    vector<vector<int>> dist(n, vector<int>(m, 1e9));
    set<pair<int, pair<int, int>>> s;
    s.insert({0, {0, 0}});
    dist[0][0] = 0;
    vector<int> dir{0, -1, 0, 1, 0};
    while (!s.empty()) {
        auto [dis, cor] = *s.begin();
        s.erase(s.begin());
        auto [i, j] = cor;
        for (int k = 0; k < 4; k++) {
            int x = i + dir[k], y = j + dir[k + 1];
            if (x >= 0 and x < n and y >= 0 and y < m and
                dist[x][y] > dist[i][j] + abs(mat[x][y] - mat[i][j])) {
                if (s.find({dist[x][y], {x, y}}) != s.end()) {
                    s.erase(s.find({dist[x][y], {x, y}}));
                }
                dist[x][y] = dist[i][j] + abs(mat[x][y] - mat[i][j]);
                s.insert({dist[x][y], {x, y}});
            }
        }
    }
    return dist[n - 1][m - 1];
}
                    


                        Solution in Java :

import java.util.*;

class Solution {
    class Node {
        int r, c;
        long dist;
        Node(int r, int c, long dist) {
            this.r = r;
            this.c = c;
            this.dist = dist;
        }
    }
    boolean valid(int r, int c, int m, int n) {
        if (r < 0 || c < 0 || r >= m || c >= n)
            return false;
        return true;
    }
    int[] dr = {0, 0, 1, -1};
    int[] dc = {1, -1, 0, 0};
    public int solve(int[][] matrix) {
        int m = matrix.length, n = matrix[0].length;
        PriorityQueue<Node> pq = new PriorityQueue<Node>((a, b) -> (Long.compare(a.dist, b.dist)));
        boolean[][] vis = new boolean[m][n];
        long[][] dists = new long[m][n];
        for (int i = 0; i < m; i++) Arrays.fill(dists[i], 100000000);
        vis[0][0] = false;
        pq.add(new Node(0, 0, 0));
        dists[0][0] = 0;
        while (pq.size() > 0 && !vis[m - 1][n - 1]) {
            Node curnode = pq.poll();
            int r = curnode.r;
            int c = curnode.c;
            long d = curnode.dist;
            if (vis[r][c])
                continue;
            vis[r][c] = true;
            for (int z = 0; z < 4; z++) {
                int nr = r + dr[z];
                int nc = c + dc[z];
                if (!valid(nr, nc, m, n) || vis[nr][nc])
                    continue;
                if (d + Math.abs(matrix[r][c] - matrix[nr][nc]) < dists[nr][nc]) {
                    dists[nr][nc] = d + Math.abs(matrix[r][c] - matrix[nr][nc]);
                    pq.add(new Node(nr, nc, dists[nr][nc]));
                }
            }
        }

        return (int) dists[m - 1][n - 1];
    }
}
                    


                        Solution in Python : 
                            
class Solution:
    def solve(self, matrix):
        m, n = len(matrix), len(matrix[0])

        def neighbours(i, j):
            dr = ((i + 1, j), (i - 1, j), (i, j - 1), (i, j + 1))
            return [(x, y) for x, y in dr if 0 <= x < m and 0 <= y < n]

        visited = [[False for j in range(n)] for i in range(m)]
        distance = [[float("inf") for j in range(n)] for i in range(m)]
        distance[0][0] = 0
        pq = []
        heapq.heapify(pq)
        heapq.heappush(pq, (0, 0, 0))  # (distance,i index, j index)
        while not visited[m - 1][n - 1]:
            dist, i, j = heapq.heappop(pq)
            if visited[i][j]:
                continue
            visited[i][j] = True
            if i == m - 1 and j == n - 1:
                break
            for x, y in neighbours(i, j):
                dist = distance[i][j] + abs(matrix[i][j] - matrix[x][y])
                if not visited[x][y] and dist < distance[x][y]:
                    distance[x][y] = dist
                    heapq.heappush(pq, (dist, x, y))
        return dist
                    


View More Similar Problems

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 →

Compare two linked lists

You’re given the pointer to the head nodes of two linked lists. Compare the data in the nodes of the linked lists to check if they are equal. If all data attributes are equal and the lists are the same length, return 1. Otherwise, return 0. Example: list1=1->2->3->Null list2=1->2->3->4->Null The two lists have equal data attributes for the first 3 nodes. list2 is longer, though, so the lis

View Solution →