-
Notifications
You must be signed in to change notification settings - Fork 0
/
find the city.cpp
50 lines (43 loc) · 1.69 KB
/
find the city.cpp
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
38
39
40
41
42
43
44
45
46
47
48
49
50
class Solution {
public:
int findTheCity(int n, vector<vector<int>>& edges, int distanceThreshold) {
vector<vector<int>> dist(n, vector<int>(n, numeric_limits<int>::max()));
// Distance to itself is 0
for (int i = 0; i < n; ++i) {
dist[i][i] = 0;
}
// Populate the distance matrix with the given edges
for (const auto& edge : edges) {
int u = edge[0], v = edge[1], w = edge[2];
dist[u][v] = w;
dist[v][u] = w;
}
// Floyd-Warshall algorithm
for (int k = 0; k < n; ++k) {
for (int i = 0; i < n; ++i) {
for (int j = 0; j < n; ++j) {
if (dist[i][k] != numeric_limits<int>::max() && dist[k][j] != numeric_limits<int>::max()) {
dist[i][j] = min(dist[i][j], dist[i][k] + dist[k][j]);
}
}
}
}
// Find the city with the smallest number of reachable cities
// and if there is a tie, choose the city with the greatest number.
int minReachableCities = numeric_limits<int>::max();
int bestCity = -1;
for (int i = 0; i < n; ++i) {
int reachableCities = 0;
for (int j = 0; j < n; ++j) {
if (dist[i][j] <= distanceThreshold) {
reachableCities++;
}
}
if (reachableCities <= minReachableCities) {
minReachableCities = reachableCities;
bestCity = i;
}
}
return bestCity;
}
};