Connected Road to Destination- Google Top Interview Questions
Problem Statement :
You are given integers sx, sy, ex, ey and two-dimensional list of integers roads. You are currently located at coordinate (sx, sy) and want to move to destination (ex, ey). Each element in roads contains (x, y) which is a road that will be added at that coordinate. Roads are added one by one in order. You can only move to adjacent (up, down, left, right) coordinates if there is a road in that coordinate or if it's the destination coordinate. For example, at (x, y) we can move to (x + 1, y) if (x + 1, y) is a road or the destination. Return the minimum number of roads in order that must be added before there is a path consisting of roads that allows us to get to (ex, ey) from (sx, sy). If there is no solution, return -1. Constraints 0 ≤ n ≤ 100,000 where n is the length of roads Example 1 Input sx = 0 sy = 0 ex = 1 ey = 2 roads = [ [9, 9], [0, 1], [0, 2], [0, 3], [3, 3] ] Output 3 Explanation We need to add the first three roads which allows us to go from (0, 0), (0, 1), (0, 2), (1, 2). Note that we must take (9, 9) since roads must be added in order.
Solution :
Solution in C++ :
pair<int, int> directions[] = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};
int solve(int sx, int sy, int ex, int ey, vector<vector<int>>& roads) {
map<pair<int, int>, int> Roads;
const int n = (int)roads.size();
for (int i = 0; i < n; i++) Roads[{roads[i][0], roads[i][1]}] = i + 1;
Roads[{ex, ey}] = 0;
priority_queue<tuple<int, int, int>, vector<tuple<int, int, int>>, greater<>> q;
q.push({0, sx, sy});
map<pair<int, int>, int> cost;
cost[{sx, sy}] = 0;
while (!q.empty()) {
auto [curr_index, x, y] = q.top();
q.pop();
if (x == ex && y == ey) return curr_index;
for (auto [dx, dy] : directions) {
int nx = x + dx;
int ny = y + dy;
if (Roads.count({nx, ny})) {
if (!cost.count({nx, ny}) || cost[{nx, ny}] > max(Roads[{nx, ny}], curr_index)) {
cost[{nx, ny}] = max(Roads[{nx, ny}], curr_index);
q.push({cost[{nx, ny}], nx, ny});
}
}
}
}
return -1;
}
Solution in Java :
import java.util.*;
class Solution {
public int solve(int sx, int sy, int ex, int ey, int[][] roads) {
if (sx == ex && sy == ey) {
return 0;
}
// We sort by the number of roads the current destination needs
Queue<int[]> q = new PriorityQueue<>((a, b) -> a[2] - b[2]);
// Use to hash/store each road
long time = (long) (1e9);
// The has for target
long target = ex * time + ey;
Map<Long, Integer> road = new HashMap<>();
Set<Long> visit = new HashSet<>();
// Store each road into the map
int count = 1;
for (int[] row : roads) {
road.put(row[0] * time + row[1], count++);
}
// [x , y , number of roads]
q.offer(new int[] {sx, sy, 0});
while (!q.isEmpty()) {
int[] cur = q.poll();
long num = cur[0] * time + cur[1];
// If visited, skip
if (visit.contains(num)) {
continue;
}
visit.add(num);
// each hashcode for each move (up,down,left,right)
long num1 = (cur[0] - 1) * time + cur[1];
long num2 = (cur[0] + 1) * time + cur[1];
long num3 = (cur[0]) * time + cur[1] - 1;
long num4 = (cur[0]) * time + cur[1] + 1;
// if any of them is equal to the target, then we return the number of roads
if (num1 == target || num2 == target || num3 == target || num4 == target) {
return cur[2];
}
// If the road map contains up/down/left/right move, put it into the pq with the number
// of roads it need to build.
if (road.containsKey(num1)) {
q.offer(new int[] {cur[0] - 1, cur[1], Math.max(cur[2], road.get(num1))});
}
if (road.containsKey(num2)) {
q.offer(new int[] {cur[0] + 1, cur[1], Math.max(cur[2], road.get(num2))});
}
if (road.containsKey(num3)) {
q.offer(new int[] {cur[0], cur[1] - 1, Math.max(cur[2], road.get(num3))});
}
if (road.containsKey(num4)) {
q.offer(new int[] {cur[0], cur[1] + 1, Math.max(cur[2], road.get(num4))});
}
}
return -1;
}
}
Solution in Python :
class Solution:
def solve(self, sx, sy, ex, ey, roads):
parent = {}
seen = set()
# Find
def ufind(x, y):
if (x, y) not in parent:
parent[(x, y)] = (x, y)
return (x, y)
if parent[(x, y)] == (x, y):
return (x, y)
d = parent[(x, y)]
p = ufind(d[0], d[1])
parent[(x, y)] = p
return p
# Union
def uunion(x1, y1, x2, y2):
p1 = ufind(x1, y1)
p2 = ufind(x2, y2)
parent[p2] = parent[p1]
directions = [(0, 1), (1, 0), (-1, 0), (0, -1)]
for dx, dy in directions:
nx, ny = sx + dx, sy + dy
if (nx, ny) == (ex, ey):
return 0
seen.add((sx, sy))
seen.add((ex, ey))
for index, (x, y) in enumerate(roads):
# Look at neighbors
for dx, dy in directions:
nx, ny = x + dx, y + dy
if (nx, ny) in seen:
uunion(x, y, nx, ny)
seen.add((x, y))
if ufind(ex, ey) == ufind(sx, sy):
return index + 1
return -1
View More Similar Problems
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 →AND xor OR
Given an array of distinct elements. Let and be the smallest and the next smallest element in the interval where . . where , are the bitwise operators , and respectively. Your task is to find the maximum possible value of . Input Format First line contains integer N. Second line contains N integers, representing elements of the array A[] . Output Format Print the value
View Solution →Waiter
You are a waiter at a party. There is a pile of numbered plates. Create an empty answers array. At each iteration, i, remove each plate from the top of the stack in order. Determine if the number on the plate is evenly divisible ith the prime number. If it is, stack it in pile Bi. Otherwise, stack it in stack Ai. Store the values Bi in from top to bottom in answers. In the next iteration, do the
View Solution →Queue using Two Stacks
A queue is an abstract data type that maintains the order in which elements were added to it, allowing the oldest elements to be removed from the front and new elements to be added to the rear. This is called a First-In-First-Out (FIFO) data structure because the first element added to the queue (i.e., the one that has been waiting the longest) is always the first one to be removed. A basic que
View Solution →Castle on the Grid
You are given a square grid with some cells open (.) and some blocked (X). Your playing piece can move along any row or column until it reaches the edge of the grid or a blocked cell. Given a grid, a start and a goal, determine the minmum number of moves to get to the goal. Function Description Complete the minimumMoves function in the editor. minimumMoves has the following parameter(s):
View Solution →Down to Zero II
You are given Q queries. Each query consists of a single number N. You can perform any of the 2 operations N on in each move: 1: If we take 2 integers a and b where , N = a * b , then we can change N = max( a, b ) 2: Decrease the value of N by 1. Determine the minimum number of moves required to reduce the value of N to 0. Input Format The first line contains the integer Q.
View Solution →