LeetCode 3243: Shortest Distance After Road Addition Queries I Solution
Master LeetCode problem 3243 (Shortest Distance After Road Addition Queries I), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.
3243. Shortest Distance After Road Addition Queries I
Problem Explanation
Explanation:
To solve this problem, we can use Dijkstra's algorithm to find the shortest path from city 0 to city n - 1 after each query. Initially, we have a unidirectional road from city i to city i + 1 for all 0 <= i < n - 1. We can represent this as a graph where each city is a node and each road is a directed edge.
For each query, we add a new road from city ui to city vi and update the graph. Then, we run Dijkstra's algorithm to find the shortest path from city 0 to city n - 1. We repeat this process for each query and store the length of the shortest path after each query.
:
Solution Code
class Solution {
public int[] shortestDistance(int n, int[][] queries) {
List<Integer>[] adjList = new ArrayList[n];
for (int i = 0; i < n; i++) {
adjList[i] = new ArrayList<>();
if (i < n - 1) {
adjList[i].add(i + 1);
}
}
int[] result = new int[queries.length];
int[] distances = new int[n];
Arrays.fill(distances, Integer.MAX_VALUE);
distances[0] = 0;
for (int i = 0; i < queries.length; i++) {
int u = queries[i][0];
int v = queries[i][1];
adjList[u].add(v);
PriorityQueue<Integer> pq = new PriorityQueue<>((a, b) -> distances[a] - distances[b]);
pq.offer(0);
while (!pq.isEmpty()) {
int curr = pq.poll();
for (int neighbor : adjList[curr]) {
int newDist = distances[curr] + 1;
if (newDist < distances[neighbor]) {
distances[neighbor] = newDist;
pq.offer(neighbor);
}
}
}
result[i] = distances[n - 1];
}
return result;
}
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 3243 (Shortest Distance After Road Addition Queries I)?
This page provides optimized solutions for LeetCode problem 3243 (Shortest Distance After Road Addition Queries I) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.
What is the time complexity of LeetCode 3243 (Shortest Distance After Road Addition Queries I)?
The time complexity for LeetCode 3243 (Shortest Distance After Road Addition Queries I) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 3243 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 3243 in Java, C++, or Python.