There are N
network nodes, labelled 1
to N
.
Given times
, a list of travel times as directed edges times[i] = (u, v, w)
, where u
is the source node, v
is the target node, and w
is the time it takes for a signal to travel from source to target.
Now, we send a signal from a certain node K
. How long will it take for all nodes to receive the signal? If it is impossible, return -1
.
Example 1:
Input: times = [[2,1,1],[2,3,1],[3,4,1]], N = 4, K = 2 Output: 2
Note:
N
will be in the range[1, 100]
.K
will be in the range[1, N]
.- The length of
times
will be in the range[1, 6000]
. - All edges
times[i] = (u, v, w)
will have1 <= u, v <= N
and0 <= w <= 100
.
算法一(Bellman Ford)
主要思路:外循环迭代N次,内循环对每一条边进行一次松弛操作。松弛操作:比如说对于某一个点i,di表示从起点到节点i的最短路径,那么如果di + (i节点到j节点的边长) < dj,则更新dj的值为di+边长。
class Solution {
public:
int networkDelayTime(vector<vector<int>>& times, int N, int K) {
vector<int> d(N+1,0xfffffff);
d[K] = 0;
int edges =times.size();
for(int i=1; i<=N; i++){
for(int j=0; j<edges; j++){
if(d[times[j][0]] + times[j][2] < d[times[j][1]]){
d[times[j][1]]= d[times[j][0]] + times[j][2];
}
}
}
int ret = 0;
for(int i=1; i<N+1; i++){
ret = max(ret,d[i]);
}
return ret == 0xfffffff? -1: ret;
}
};
算法二(SPFA):
主要思路:Bellman Ford是遍历所有的边,SPFA是将所有收到影响的点添加到队列里,每次更新收到影响的点的值。
class Solution {
public:
int networkDelayTime(vector<vector<int>>& times, int N, int K) {
vector<int> d(N+1,0xfffffff);
vector<bool> isInQueue(N+1,false);
vector<vector<pair<int,int>>> graph(N+1, vector<pair<int,int>>());
for(int i=0; i<times.size(); i++){
int u = times[i][0];
int v = times[i][1];
int w = times[i][2];
graph[u].emplace_back(v,w);
}
queue<int>q;
d[K] = 0;
q.push(K);
while(!q.empty()){
int u = q.front(); q.pop();
isInQueue[u] = false;
for(auto &t: graph[u]){
if(d[u]+t.second < d[t.first]){
d[t.first] = d[u] + t.second;
if(isInQueue[t.first] == false){
isInQueue[t.first] = true;
q.push(t.first);
}
}
}
}
int ret = 0;
for(int i=1; i<N+1; i++){
ret = max(ret,d[i]);
}
return ret == 0xfffffff? -1: ret;
}
};