题目描述
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.
Example 1:
Input: n = 4, edges = [[0,1,3],[1,2,1],[1,3,4],[2,3,1]], distanceThreshold = 4
Output: 3
Explanation: The figure above describes the graph.
The neighboring cities at a distanceThreshold = 4 for each city are:
City 0 -> [City 1, City 2]
City 1 -> [City 0, City 2, City 3]
City 2 -> [City 0, City 1, City 3]
City 3 -> [City 1, City 2]
Cities 0 and 3 have 2 neighboring cities at a distanceThreshold = 4, but we have to return city 3 since it has the greatest number.
Example 2:
Input: n = 5, edges = [[0,1,2],[0,4,8],[1,2,3],[1,4,2],[2,3,1],[3,4,1]], distanceThreshold = 2
Output: 0
Explanation: The figure above describes the graph.
The neighboring cities at a distanceThreshold = 2 for each city are:
City 0 -> [City 1]
City 1 -> [City 0, City 4]
City 2 -> [City 3, City 4]
City 3 -> [City 2, City 4]
City 4 -> [City 1, City 2, City 3]
The city 0 has 1 neighboring city at a distanceThreshold = 2.
Constraints:
2 <= n <= 100
1 <= edges.length <= n * (n - 1) / 2
edges[i].length == 3
0 <= fromi < toi < n
1 <= weighti, distanceThreshold <= 10^4
All pairs (fromi, toi) are distinct.
思路
先用 floyed 算法求出任意两点之间的最短路径,然后依次统计每个点到其它点的最短距离小于阈值的个数。
代码
class Solution {
public:
int findTheCity(int n, vector<vector<int>>& edges, int distanceThreshold) {
vector<vector<int> > dp(n, vector<int>(n, INT_MAX/2));
for (auto e : edges) {
dp[e[0]][e[1]] = dp[e[1]][e[0]] = e[2];
}
for (int k=0; k<n; ++k) {
for (int u=0; u<n; ++u) {
for (int v=0; v<n; ++v) {
dp[u][v] = min(dp[u][v], dp[u][k]+dp[k][v]);
}
}
}
int min_nb = INT_MAX;
int ans;
for (int u=0; u<n; ++u) {
int nb = 0;
for (int v=0; v<n; ++v) {
if (u == v) continue;
if (dp[u][v] <= distanceThreshold) {
nb++;
}
}
if (nb <= min_nb) {
min_nb = nb;
ans = u;
}
}
return ans;
}
};

本文介绍了一种使用Floyd算法解决城市间最短路径问题的方法,旨在找到在给定距离阈值下,可达城市数量最少且编号最大的城市。通过实例演示了如何计算各城市间的最短路径,并统计每个城市在距离阈值限制下的可达城市数量。

被折叠的 条评论
为什么被折叠?



