Find the City With the Smallest Number of Neighbors at a Threshold Distance
Master this topic with zero to advance depth.
Find the City With the Smallest Number of Neighbors at a Threshold Distance
There are n cities numbered from 0 to n-1. Given the array edges where edges[i] = [from_i, to_i, weight_i] represents a bidirectional weighted edge between cities from_i and to_i, and given the integer distanceThreshold.
Return the city with the smallest number of cities that are reachable through some path and whose distance is at most distanceThreshold. If there are multiple such cities, return the city with the greatest number.
Visual Representation
Cities 4, Edges: [[0,1,3],[1,2,1],[1,3,4],[2,3,1]], Threshold 4
0 --3-- 1 --1-- 2
\ /
4---3
(1)
City 0: Neighbors {1,2} (Dist 3, 4) - Count 2
City 3: Neighbors {1,2} (Dist 2, 1) - Count 2
... compare all, find min count.Examples
City 3 has 2 neighbors within distance 4, same as city 0, but 3 > 0.
Level III: Optimal (Floyd-Warshall Algorithm)
Intuition
This problem requires finding all-pairs shortest paths to count how many cities are within the threshold for each city. Floyd-Warshall is the standard algorithm for all-pairs shortest paths in a small number of vertices ().
Thought Process
- Initialize a
distmatrix of size with infinity, anddist[i][i] = 0. - For each edge
(u, v, w), setdist[u][v] = dist[v][u] = w. - Run Floyd-Warshall: three nested loops
k, i, jto updatedist[i][j] = min(dist[i][j], dist[i][k] + dist[k][j]). - For each city
i, count how manyjhavedist[i][j] <= distanceThreshold. - Tracking the minimum count and the maximum index among cities with that count.
Pattern: All-Pairs Shortest Path
Detailed Dry Run
N=4, Threshold=4
- After Floyd-Warshall, dist[0][1]=3, dist[0][2]=4, dist[0][3]=5.
- City 0 count (<= 4): 2 (cities 1 and 2).
- City 3 count (<= 4): dist[3][1]=2, dist[3][2]=1, dist[3][0]=5. Count 2 (cities 1 and 2).
- Since counts are equal, pick city 3 (larger index).
Found an issue or have a suggestion?
Help us improve! Report bugs or suggest new features on our Telegram group.