Find the City With the Smallest Number of Neighbors at a Threshold Distance

There are `n` cities numbered `0` to `n - 1`. `edges[i] = [from_i, to_i, weight_i]` is a bidirectional, weighted road between two cities, and `distanceThreshold` is an integer. Return the city with the smallest number of cities reachable through some path whose total distance is at most `distanceThreshold`. If several cities tie, return the one with the greatest number.

30:00

Find the City With the Smallest Number of Neighbors at a Threshold Distance
medium
Free written solution
Topics
Companies

There are n cities numbered 0 to n - 1. edges[i] = [from_i, to_i, weight_i] is a bidirectional, weighted road between two cities, and distanceThreshold is an integer. Return the city with the smallest number of cities reachable through some path whose total distance is at most distanceThreshold. If several cities tie, return the one with the greatest number.

Example 1:
Input: {"n":4,"edges":[[0,1,3],[1,2,1],[1,3,4],[2,3,1]],"distanceThreshold":4}
Output: 3
Constraints:
  • 2≤n≤1002 \leq n \leq 100

  • 1≤edges.length≤n(n−1)/21 \leq \text{edges.length} \leq n (n - 1) / 2

  • edges[i].length==3\text{edges}[i].\text{length} == 3

  • 0≤fromi<toi<n0 \leq \text{from}_i < \text{to}_i < n

  • 1≤weighti,distanceThreshold≤1041 \leq \text{weight}_i, \text{distanceThreshold} \leq 10^4

  • All pairs (fromi,toi)(\text{from}_i, \text{to}_i) are distinct

Test Cases
Input (Stdin)
Expected Output (Stdout)
Execution Result

Run code to see results.

Input
arr ={"n":4,"edges":[[0,1,3],[1,2,1],[1,3,4],[2,3,1]],"distanceThreshold":4}

Fill the distance table with the 4 direct roads; every other pair starts at infinity. Floyd-Warshall will try each city as a stopover.

threshold

4

stopover k

-

best city

-

best count

-

roads, stopover in amber

31410123

dist[i][j]

0
1
2
3
0
0
3
∞
∞
1
3
0
1
4
2
∞
1
0
1
3
∞
4
1
0
Variables
VariableValue
n4
roads4
threshold4
DepthFunction Call
Stack empty
0/9