There are n cities (0 .. n-1) connected by bidirectional weighted edges[i] = [u, v, w]. Return the city with the smallest number of other cities reachable within a total distance ≤ threshold. If several cities tie, return the one with the greatest index.
Input: n = 4, edges = [[0,1,3],[1,2,1],[2,3,4],[0,3,7]], threshold = 4 Output: 3 City 3 reaches only city 2 within distance 4 — the fewest.
Input: n = 5, edges = [[0,1,2],[0,4,8],[1,2,3],[1,4,2],[2,3,1],[3,4,1]], threshold = 2 Output: 0 City 0 reaches the fewest (just city 1) within distance 2.
- 1 <= n <= 100 - 0 <= edges.length <= n*(n-1)/2 - 1 <= w <= 10^4 - 0 <= threshold <= 10^4
Two questions stack here: all-pairs shortest distances, then count and choose. Compute the distance between every pair (Floyd-Warshall is the tidy choice), then for each city count how many others sit within threshold. Return the city with the fewest such neighbours, breaking ties toward the largest index — which you get for free by scanning 0 .. n-1 and using a ≤ comparison so a later city overwrites an equal earlier one.
Floyd-Warshall is O(n³); the brute alternative runs Dijkstra from every city for the same all-pairs matrix, O(n·(n+E) log n). Both feed the identical count-and-pick step.
“Count includes the city itself?”
No — only other reachable cities.
“Tie-breaking?”
Return the city with the greatest index.
I compute all-pairs shortest distances with Floyd-Warshall, then count each city's neighbours within the threshold.
I return the city with the fewest, scanning in order with ≤ so the largest index wins ties.
Worked example — n = 4, edges [[0,1,3],[1,2,1],[2,3,4],[0,3,7]], threshold = 4
city 3 reaches {2} within 4 -> count 1 (fewest); it's also the largest index
answer = 3
Multi-hop routes can fall under the threshold.
Fewest reachable neighbours wins.
A later equal city overwrites the earlier one.
| Dijkstra per city | Floyd-Warshall | |
|---|---|---|
| All-pairs via | n Dijkstra runs | one O(n³) DP |
| Time | O(n·(n+E) log n) | O(n³) |
| Then | count + pick | count + pick |
Both compute the same distances and pick the same city. Full code is in the Approaches selector below.
Key takeaway
Compute all-pairs shortest distances (Floyd-Warshall), count each city's neighbours within threshold, and return the city with the fewest — largest index on ties. O(n³).
all-pairs distances; count[i] = #{j != i : dist[i][j] <= threshold}
answer = argmin count with largest-index tie-break