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
Print the Elements of a Linked List
This is an to practice traversing a linked list. Given a pointer to the head node of a linked list, print each node's data element, one per line. If the head pointer is null (indicating the list is empty), there is nothing to print. Function Description: Complete the printLinkedList function in the editor below. printLinkedList has the following parameter(s): 1.SinglyLinkedListNode
View Solution →Insert a Node at the Tail of a Linked List
You are given the pointer to the head node of a linked list and an integer to add to the list. Create a new node with the given integer. Insert this node at the tail of the linked list and return the head node of the linked list formed after inserting this new node. The given head pointer may be null, meaning that the initial list is empty. Input Format: You have to complete the SinglyLink
View Solution →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 →