Floyd-Warshall
Time O(n³) Space O(n²)All-pairs distances; for each city count others within the threshold; pick the smallest count, preferring the larger index on ties.
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 i = 0; i < n; i++) for (int j = 0; j < n; j++) d[i][j] = i == j ? 0 : INF;
for (int[] e : edges) { d[e[0]][e[1]] = e[2]; 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++)
if (d[i][k] + d[k][j] < d[i][j]) d[i][j] = d[i][k] + d[k][j];
int answer = -1, fewest = Integer.MAX_VALUE;
for (int i = 0; i < n; i++) {
int count = 0;
for (int j = 0; j < n; j++) if (i != j && d[i][j] <= distanceThreshold) count++;
if (count <= fewest) { fewest = count; answer = i; }
}
return answer;
}
}Verdict: Simplest correct choice for small n.