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 firsti + 1
queries.
Examples
Example 1:
|
|
graph LR; 0 --> 1 --> 2 --> 3 --> 4 2 --> 4
After the addition of the road from 2 to 4, the length of the shortest path from 0 to 4 is 3.
graph LR; 0 --> 1 --> 2 --> 3 --> 4 0 --> 2 2 --> 4
After the addition of the road from 0 to 2, the length of the shortest path from 0 to 4 is 2.
%%{init: {'flowchart' : {'curve' : 'linear'}}}%% flowchart-elk LR 0 --> 1 --> 2 --> 3 --> 4 0 --> 2 2 --> 4 0 --> 4
After the addition of the road from 0 to 4, the length of the shortest path from 0 to 4 is 1.
Example 2:
|
|
Explanation:
graph LR; 0 --> 1 --> 2 --> 3 0 --> 3
After the addition of the road from 0 to 3, the length of the shortest path from 0 to 3 is 1.
flowchart-elk LR; 0 --> 1 --> 2 --> 3 0 --> 3 0 --> 2
After the addition of the road from 0 to 2, the length of the shortest path remains 1.
Constraints:
3 <= n <= 500
1 <= queries.length <= 500
queries[i].length == 2
0 <= queries[i][0] < queries[i][1] < n
1 < queries[i][1] - queries[i][0]
- There are no repeated roads among the queries.
Solution
Method 1 - Using BFS
The core idea is to maintain the shortest path length from city 0 to city n-1 as we continuously add new roads specified by the queries. Note that initially, the shortest path is the direct path from 0 to n-1 which is of length n-1
.
- Initial Setup: The cities are connected in a linear fashion from 0 to n-1, so the initial shortest path is the direct route which is of length
n-1
. - Applying Queries: For each query
[ui, vi]
, we add the new road from cityui
to cityvi
and then determine if this reduces the shortest path from 0 to n-1. - Shortest Path Calculation: Use a Breadth-First Search (BFS) or Dijkstra’s algorithm to dynamically find the shortest path after each query is applied.
Code
|
|
|
|
Complexity
- ⏰ Time complexity: The BFS or Dijkstra’s algorithm used to find the shortest path will take
O(V + E)
whereV
is the number of cities andE
is the number of roads (including the new roads added). Givenq
queries, the overall complexity would beO(q * (V + E))
. - 🧺 Space complexity: The space required by the BFS/Dijkstra’s algorithm includes the space for the graph representation and the data structures used in BFS/Dijkstra, giving a total of
O(V + E)
space.