Advanced Graphs Weighted shortest paths
475. Find the City With the Smallest Number of Neighbors at a Threshold Distance
There are n cities, numbered from 0 to n − 1. You are given a list edges of roads, where
edges[i] = [u, v, w] is a road of length w between cities u and v. A road can be used in both
directions.
The distance between two cities is the length of the shortest route between them, over any number of roads.
For each city, count the other cities whose distance from it is at most distanceThreshold. Return the city
with the smallest count. If several cities share the smallest count, return the one with the largest number.
A city that no route reaches is never counted, however large the threshold is.
Example 1
Input: n = 6
edges = [[0, 1, 2],
[1, 2, 2],
[2, 3, 3],
[3, 4, 2],
[4, 5, 6],
[0, 5, 1]]
distanceThreshold = 4
4Explanation: City 4 reaches only city 3 within a distance of 4. City 2 is 5 away from it and city 5 is 6 away. Every other city reaches at least two cities: city 5, for example, reaches city 0 at 1 and city 1 at 3.
Example 2
Input: n = 5
edges = [[0, 1, 2], [1, 2, 2], [3, 4, 1]]
distanceThreshold = 4
4Explanation: Cities 0, 1 and 2 each reach the other two, since city 0 is 4 away from city 2. Cities 3 and 4 are joined only to each other, so each has one. They tie, and the answer is the larger number, 4.
Example 3
Input: n = 4
edges = [[0, 1, 4],
[1, 2, 6],
[2, 3, 1],
[0, 1, 9]]
distanceThreshold = 10
3Explanation: Two roads join cities 0 and 1, and the shorter one, of length 4, is the one a route uses. City 0 then reaches city 2 at exactly 4 + 6 = 10, which counts. Cities 0 and 3 both reach two cities, so the answer is 3.
Check your understanding
Work out the answer for this input before you write any code.
Constraints
1 ≤ n ≤ 4000 ≤ edges.length ≤ 105edges[i] = [u, v, w], with0 ≤ u, v ≤ n − 1,u ≠ vand1 ≤ w ≤ 1041 ≤ distanceThreshold ≤ 104- Two roads can join the same two cities.
Clarifying questions
What you would ask an interviewer before writing any code.