Skip to main content
Back to problems
#1334
Medium Algorithms

Find the city with the smallest number of neighbors at a threshold distance

Dynamic Programming Graph Theory Shortest Path
72.2% acceptance
Feb 25, 2026
3597
155
There are n cities numbered from 0 to n-1. Given the array edges where edges[i] = [fromi, toi, weighti] represents a bidirectional and weighted edge between cities fromi and toi, 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. Notice that the distance of a path connecting cities i and j is equal to the sum of the edges' weights along that path.

Solution

Rust
Time O(n * m)
Space O(n * m)
LeetCode
solution.rs
impl Solution {
  pub fn find_the_city(n: i32, edges: Vec<Vec<i32>>, distance_threshold: i32) -> i32 {
    let n = n as usize;
    const INF: i32 = i32::MAX / 2;
    let mut dist = vec![vec![INF; n]; n];
    for i in 0..n { dist[i][i] = 0; }
    for e in &edges {
      let (u, v, w) = (e[0] as usize, e[1] as usize, e[2]);
      dist[u][v] = w;
      dist[v][u] = w;
    }
    // Floyd-Warshall
    for k in 0..n {
      for i in 0..n {
        for j in 0..n {
          if dist[i][k] < INF && dist[k][j] < INF {
            dist[i][j] = dist[i][j].min(dist[i][k] + dist[k][j]);
          }
        }
      }
    }
    let mut ans = 0;
    let mut min_count = n + 1;
    for i in 0..n {
      let count = (0..n).filter(|&j| j != i && dist[i][j] <= distance_threshold).count();
      if count <= min_count {
        min_count = count;
        ans = i;
      }
    }
    ans as i32
  }
}