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
Merging Communities
People connect with each other in a social network. A connection between Person I and Person J is represented as . When two persons belonging to different communities connect, the net effect is the merger of both communities which I and J belongs to. At the beginning, there are N people representing N communities. Suppose person 1 and 2 connected and later 2 and 3 connected, then ,1 , 2 and 3 w
View Solution →Components in a graph
There are 2 * N nodes in an undirected graph, and a number of edges connecting some nodes. In each edge, the first value will be between 1 and N, inclusive. The second node will be between N + 1 and , 2 * N inclusive. Given a list of edges, determine the size of the smallest and largest connected components that have or more nodes. A node can have any number of connections. The highest node valu
View Solution →Kundu and Tree
Kundu is true tree lover. Tree is a connected graph having N vertices and N-1 edges. Today when he got a tree, he colored each edge with one of either red(r) or black(b) color. He is interested in knowing how many triplets(a,b,c) of vertices are there , such that, there is atleast one edge having red color on all the three paths i.e. from vertex a to b, vertex b to c and vertex c to a . Note that
View Solution →Super Maximum Cost Queries
Victoria has a tree, T , consisting of N nodes numbered from 1 to N. Each edge from node Ui to Vi in tree T has an integer weight, Wi. Let's define the cost, C, of a path from some node X to some other node Y as the maximum weight ( W ) for any edge in the unique path from node X to Y node . Victoria wants your help processing Q queries on tree T, where each query contains 2 integers, L and
View Solution →Contacts
We're going to make our own Contacts application! The application must perform two types of operations: 1 . add name, where name is a string denoting a contact name. This must store name as a new contact in the application. find partial, where partial is a string denoting a partial name to search the application for. It must count the number of contacts starting partial with and print the co
View Solution →No Prefix Set
There is a given list of strings where each string contains only lowercase letters from a - j, inclusive. The set of strings is said to be a GOOD SET if no string is a prefix of another string. In this case, print GOOD SET. Otherwise, print BAD SET on the first line followed by the string being checked. Note If two strings are identical, they are prefixes of each other. Function Descriptio
View Solution →