743. 网络延迟时间(https://leetcode-cn.com/problems/network-delay-time/)
有 n 个网络节点,标记为 1 到 n。
给你一个列表 times,表示信号经过 有向 边的传递时间。 times[i] = (ui, vi, wi),其中 ui 是源节点,vi 是目标节点, wi 是一个信号从源节点传递到目标节点的时间。
现在,从某个节点 K 发出一个信号。需要多久才能使所有节点都收到信号?如果不能使所有节点收到信号,返回 -1 。
示例 1:
输入:times = [[2,1,1],[2,3,1],[3,4,1]], n = 4, k = 2
输出:2
示例 2:
输入:times = [[1,2,1]], n = 2, k = 1
输出:1
示例 3:
输入:times = [[1,2,1]], n = 2, k = 2
输出:-1
提示:
1 <= k <= n <= 100
1 <= times.length <= 6000
times[i].length == 3
1 <= ui, vi <= n
ui != vi
0 <= wi <= 100
所有 (ui, vi) 对都 互不相同(即,不含重复边)
分析题意:直接搜不就完事儿?
~~果断WA掉,通过WA掉的数据发现,从起点到某个节点可能多种路径,我们要选最短的那条,那么,这就是单源起点最短路径问题了,最终取所有最短路径中最大值
AC代码:
class Solution {
public:
int networkDelayTime(vector<vector<int>>& times, int n, int k) {
bool vis[105]={0};
vector<pair<int,int>>mp[105];
for(auto &v:times){
mp[v[0]].push_back({v[1],v[2]});
}
int shortest[105];
memset(shortest,0x3f,sizeof shortest);
for(auto &v:mp[k]) shortest[v.first]=v.second;
vis[k]=1;
for(int i=1;i<=n;i++){
int key,sot=INT_MAX;
for(int j=1;j<=n;j++)
{
if(!vis[j]&&shortest[j]<sot){
sot=shortest[j];
key=j;
}
}
vis[key]=1;
for(auto &v:mp[key]){
if(!vis[v.first]&&v.second+sot<shortest[v.first]){
shortest[v.first]=v.second+sot;
}
}
}
int res=0;
for(int i=1;i<=n;i++){
if(i==k) continue;
res=max(shortest[i],res);
}
if(res>=0x3f3f3f3f) res=-1;
return res;
}
};