743. Network Delay Time
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.
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 have 1 <= u, v <= N and 1 <= w <= 100.
解题思路
使用Bellman-Ford算法来求最短路径。
- 首先将源点K到其他节点的路径长度设为无穷大(本题中设置为了10000表示无穷大)。
- 遍历所有节点对,如果这对节点中的源节点已经被遍历(即K到其距离小于无穷),则这对节点中的目标节点可以达到。
- 比较这对节点中的目标节点的路径长和源节点加权值的大小。
- 遍历N-1次后结束。
- 如果路径中存在无穷大,则表明有的节点是不可达的,返回-1,否则返回路径中最大的一个。
代码如下:
class Solution {
public:
int networkDelayTime(vector<vector<int>>& times, int N, int K) {
vector<int> dist(N+1, 10000);
dist[K] = 0;
int max_loop = times.size();
int t = 1;
int full_loop = 0;
while(t++ && full_loop < N) {
if(t > max_loop + 1) {
full_loop++;
t = 2;
}
vector<int> time = times[t-2];
int u = time[0];
int v = time[1];
int w = time[2];
if(dist[u] != 10000 && dist[v] > dist[u] + w) {
dist[v] = dist[u] + w;
continue;
}
}
int result = 0;
for(int i = 1; i <= N; i++) {
if(dist[i] > result) {
result = dist[i];
}
}
if(result == 10000) {
result = -1;
}
return result;
}
};