Example 1
- Input
- n = 4, edges = [[0,1,3],[1,2,1],[1,3,4],[2,3,1]], distanceThreshold = 4
- Output
- 3
The reachable sets excluding self are {1,2}, {0,2,3}, {0,1,3}, {1,2}. Cities 0 and 3 each have two neighbors; the larger index 3 wins.
Find the city with the fewest other cities reachable within a distance threshold in an undirected weighted graph. Break ties by choosing the largest city number.
There are n cities numbered from 0 to n - 1. Each entry [u, v, weight] in edges is a bidirectional road. A path’s distance is the sum of its road weights.
Return the city with the smallest count of other cities reachable by a path of total distance at most distanceThreshold. If several cities share the minimum count, return the largest index. A city does not count itself; unreachable cities never count.
2 <= n <= 1001 <= edges.length <= n * (n - 1) / 2; each edge has three integers.0 <= u < v < n; all endpoint pairs are distinct.1 <= weight, distanceThreshold <= 10^4The reachable sets excluding self are {1,2}, {0,2,3}, {0,1,3}, {1,2}. Cities 0 and 3 each have two neighbors; the larger index 3 wins.
The only road exceeds the threshold. Both cities count zero neighbors, so the tie chooses 1.
Cities 0, 1 and 2 each reach the other two within distance 2. Isolated city 3 reaches nobody, so it uniquely minimizes the count.
A road may be expensive even when a cheaper indirect route exists. In Example 1, the road from 1 to 3 costs 4, but traveling through 2 costs 2. Floyd-Warshall stores distances for every pair and allows one more intermediate city in each phase. Once all intermediates are allowed, count each row’s distances within 4: the counts are [2,3,3,2], so the larger tied index 3 wins.
Reveal Floyd-Warshall: intuition, complexity, and code
When answers depend on many pairs in a small graph, dynamic programming over allowed intermediates computes all shortest routes in one matrix.