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 :
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
The Strange Function
One of the most important skills a programmer needs to learn early on is the ability to pose a problem in an abstract way. This skill is important not just for researchers but also in applied fields like software engineering and web development. You are able to solve most of a problem, except for one last subproblem, which you have posed in an abstract way as follows: Given an array consisting
View Solution →Self-Driving Bus
Treeland is a country with n cities and n - 1 roads. There is exactly one path between any two cities. The ruler of Treeland wants to implement a self-driving bus system and asks tree-loving Alex to plan the bus routes. Alex decides that each route must contain a subset of connected cities; a subset of cities is connected if the following two conditions are true: There is a path between ever
View Solution →Unique Colors
You are given an unrooted tree of n nodes numbered from 1 to n . Each node i has a color, ci. Let d( i , j ) be the number of different colors in the path between node i and node j. For each node i, calculate the value of sum, defined as follows: Your task is to print the value of sumi for each node 1 <= i <= n. Input Format The first line contains a single integer, n, denoti
View Solution →Fibonacci Numbers Tree
Shashank loves trees and math. He has a rooted tree, T , consisting of N nodes uniquely labeled with integers in the inclusive range [1 , N ]. The node labeled as 1 is the root node of tree , and each node in is associated with some positive integer value (all values are initially ). Let's define Fk as the Kth Fibonacci number. Shashank wants to perform 22 types of operations over his tree, T
View Solution →Pair Sums
Given an array, we define its value to be the value obtained by following these instructions: Write down all pairs of numbers from this array. Compute the product of each pair. Find the sum of all the products. For example, for a given array, for a given array [7,2 ,-1 ,2 ] Note that ( 7 , 2 ) is listed twice, one for each occurrence of 2. Given an array of integers, find the largest v
View Solution →Lazy White Falcon
White Falcon just solved the data structure problem below using heavy-light decomposition. Can you help her find a new solution that doesn't require implementing any fancy techniques? There are 2 types of query operations that can be performed on a tree: 1 u x: Assign x as the value of node u. 2 u v: Print the sum of the node values in the unique path from node u to node v. Given a tree wi
View Solution →