[LeetCode] Find the City With the Smallest Number of Neighbors at a Threshold Distance

1334. 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] = [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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
class Solution {
vector<vector<int>> floydWarshall(int n, vector<vector<int>>& edges) {
vector<vector<int>> g(n, vector<int>(n, 987654321));
for(auto e : edges) {
g[e[1]][e[0]] = g[e[0]][e[1]] = min(g[e[0]][e[1]], e[2]);
}
for(int k = 0; k < n; k++) {
for(int i = 0; i < n; i++) {
for(int j = 0; j < n; j++) {
if(g[i][j] > g[i][k] + g[k][j]) {
g[i][j] = g[i][k] + g[k][j];
}
}
}
}
return g;
}
public:
int findTheCity(int n, vector<vector<int>>& edges, int distanceThreshold) {
vector<vector<int>> g = floydWarshall(n, edges);

int city = -1;
int reachable = INT_MAX;
for(int i = 0; i < n; i++) {
int r = 0;
for(int j = 0; j < n; j++) {
if(j == i) continue;
r += (g[i][j] <= distanceThreshold);
}
if(reachable >= r) {
reachable = r;
city = i;
}
}
return city;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/03/13/PS/LeetCode/find-the-city-with-the-smallest-number-of-neighbors-at-a-threshold-distance/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.