Shortest Distance After Road Addition Queries I - Problem
You are given an integer n and a 2D integer array queries. There are n cities numbered from 0 to n - 1.
Initially, there is a unidirectional road from city i to city i + 1 for all 0 <= i < n - 1.
queries[i] = [ui, vi] represents the addition of a new unidirectional road from city ui to city vi.
After each query, you need to find the length of the shortest path from city 0 to city n - 1.
Return an array answer where for each i in the range [0, queries.length - 1], answer[i] is the length of the shortest path from city 0 to city n - 1 after processing the first i + 1 queries.
Input & Output
Example 1 — Basic Case
$
Input:
n = 5, queries = [[2,4],[0,3],[0,4]]
›
Output:
[3,2,1]
💡 Note:
Initially: 0→1→2→3→4 (distance 4). After [2,4]: 0→1→2→4 (distance 3). After [0,3]: 0→3→4 (distance 2). After [0,4]: 0→4 (distance 1).
Example 2 — Single Query
$
Input:
n = 4, queries = [[0,3]]
›
Output:
[1]
💡 Note:
Initially: 0→1→2→3 (distance 3). After [0,3]: direct path 0→3 (distance 1).
Example 3 — No Improvement
$
Input:
n = 4, queries = [[1,3],[2,0]]
›
Output:
[2,2]
💡 Note:
Initially: 0→1→2→3 (distance 3). After [1,3]: 0→1→3 (distance 2). After [2,0]: still shortest is 0→1→3 (distance 2).
Constraints
- 3 ≤ n ≤ 500
- 1 ≤ queries.length ≤ 500
- queries[i].length == 2
- 0 ≤ ui < vi < n
- 1 < vi - ui
Visualization
Tap to expand
Understanding the Visualization
1
Initial State
Cities connected sequentially: 0→1→2→3→4
2
Add Roads
New roads create shortcuts between cities
3
Find Shortest
BFS finds shortest path after each addition
Key Takeaway
🎯 Key Insight: Each new road can potentially create a shorter path, so we need to recalculate the shortest distance using BFS after each addition
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code