Leet Code Daily 2024-07-26 - Find the City with the Smallest Number of Neighbors at a Threshold Distance
Solution
Floyd-Warshall Algorithm.
Code
constexpr int kFarAway = 1000000;
class Solution {
public:
int findTheCity(int n, vector<vector<int>>& edges, int distanceThreshold) {
auto distance = vector<vector<int>>(n, vector<int>(n, kFarAway));
for (int i = 0; i < n; i++) {
distance[i][i] = 0;
}
for (const auto& edge : edges) {
distance[edge[0]][edge[1]] =
min(distance[edge[0]][edge[1]], edge[2]);
distance[edge[1]][edge[0]] =
min(distance[edge[1]][edge[0]], edge[2]);
}
for (int k = 0; k < n; k++) {
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
distance[i][j] =
min(distance[i][j], distance[i][k] + distance[k][j]);
}
}
}
auto count = vector<int>(n, 0);
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if (distance[i][j] <= distanceThreshold) {
count[i]++;
}
}
}
int ret = 0;
for (int i = 1; i < n; i++) {
if (count[i] <= count[ret]) {
ret = i;
}
}
return ret;
}
};