Shortest Routes II

You are given n cities (numbered 1 to n) and a 2D array edges where edges[i] = [u, v, w] represents a two-way road between city u and city v with a length of w.

You are also given a 2D array queries where queries[j] = [a, b]. For each query, find the length of the shortest route between city a and city b. Return an array of these lengths. If there is no possible route, return -1 for that query.

Example 1:

Input: n = 3, edges = [[1, 2, 10], [1, 2, 2]], queries = [[1, 2]]

Output: [2]

Explanation:

Multiple roads connect 1 and 2. Always take the shortest one.

Example 2:

Input: n = 4, edges = [[1, 2, 5], [1, 3, 9], [2, 3, 3]], queries = [[1, 2], [2, 1], [1, 3], [1, 4], [3, 2]]

Output: [5, 5, 8, -1, 3]

Explanation:

1 to 3 via 2 costs 5 + 3 = 8 (better than the direct 9). City 4 is completely disconnected, resulting in -1.

Now Your Turn!

Pick the correct output for the given input

Input: n = 2, edges = [[1, 2, 5]], queries = [[1, 1]]

Still unsure what the problem is asking ?

Let’s go through a few more examples, step by step, to make it clearer.

Constraints:

  • 1 <= n <= 500
  • 1 <= edges.length <= n2
  • 1 <= queries.length <= 105
  • 1 <= u, v, a, b <= n
  • 1 <= w <= 109

Hints

Frequently Occurring Doubts

Interview Follow-up Questions

Fun Facts

0
class Solution {
public:
vector<long long> shortestRoute(int n, vector<vector<int>>& edges, vector<vector<int>>& queries) {
}
};
Test Case

Input:

Edges
N
Queries