1334. Find the City With the Smallest Number of Neighbors at a Threshold Distance
Problem
Cities 0…n − 1 are joined by weighted two-way edges. For each city, count the cities reachable through paths of total weight ≤ distanceThreshold. Return the city with the smallest count; on a tie, the one with the largest number.
Example: n = 4, edges = [[0,1,3],[1,2,1],[1,3,4],[2,3,1]], distanceThreshold = 4 → 3
Constraints: n ≤ 100.
All-pairs shortest paths with Floyd–Warshall (dist[i][j] = min(dist[i][j], dist[i][k] + dist[k][j]) for every intermediate k). Count reachable cities within the threshold; ties go to the larger index.
Complexity: O(n³).
class Solution:
def findTheCity(self, n: int, edges: List[List[int]], distanceThreshold: int) -> int:
INF = float("inf")
d = [[0 if i == j else INF for j in range(n)] for i in range(n)]
for a, b, w in edges:
d[a][b] = d[b][a] = w
for k in range(n):
for i in range(n):
for j in range(n):
if d[i][k] + d[k][j] < d[i][j]:
d[i][j] = d[i][k] + d[k][j]
best, city = INF, -1
for i in range(n):
cnt = sum(d[i][j] <= distanceThreshold for j in range(n)) - 1
if cnt <= best:
best, city = cnt, i
return city
assert Solution().findTheCity(4, [[0, 1, 3], [1, 2, 1], [1, 3, 4], [2, 3, 1]], 4) == 3
assert Solution().findTheCity(5, [[0, 1, 2], [0, 4, 8], [1, 2, 3], [1, 4, 2], [2, 3, 1], [3, 4, 1]], 2) == 0
class Solution {
public int findTheCity(int n, int[][] edges, int distanceThreshold) {
int INF = 1_000_000_000;
int[][] d = new int[n][n];
for (int[] row : d) Arrays.fill(row, INF);
for (int i = 0; i < n; i++) d[i][i] = 0;
for (int[] e : edges) d[e[0]][e[1]] = d[e[1]][e[0]] = e[2];
for (int k = 0; k < n; k++)
for (int i = 0; i < n; i++)
for (int j = 0; j < n; j++) d[i][j] = Math.min(d[i][j], d[i][k] + d[k][j]);
int best = Integer.MAX_VALUE, city = -1;
for (int i = 0; i < n; i++) {
int cnt = 0;
for (int j = 0; j < n; j++) if (j != i && d[i][j] <= distanceThreshold) cnt++;
if (cnt <= best) { best = cnt; city = i; }
}
return city;
}
}
func findTheCity(n int, edges [][]int, distanceThreshold int) int {
const inf = math.MaxInt32 / 2 // inf + inf must not overflow
d := make([][]int, n)
for i := range d {
d[i] = make([]int, n)
for j := range d[i] {
if i != j {
d[i][j] = inf
}
}
}
for _, e := range edges {
d[e[0]][e[1]], d[e[1]][e[0]] = e[2], e[2]
}
for k := 0; k < n; k++ { // Floyd-Warshall
for i := 0; i < n; i++ {
for j := 0; j < n; j++ {
if d[i][k]+d[k][j] < d[i][j] {
d[i][j] = d[i][k] + d[k][j]
}
}
}
}
best, city := math.MaxInt, -1
for i := 0; i < n; i++ {
cnt := 0
for j := 0; j < n; j++ {
if j != i && d[i][j] <= distanceThreshold {
cnt++
}
}
if cnt <= best { // ties go to the larger index
best, city = cnt, i
}
}
return city
}