原题

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:

  1. N will be in the range [1, 100].
  2. K will be in the range [1, N].
  3. The length of times will be in the range [1, 6000].
  4. All edges times[i] = (u, v, w) will have 1 <= u, v <= N and 1 <= w <= 100.

题解

Dijskra

本题是典型的求解最短路径的问题,我们可以用Dijsktra方法进行求解。

Dijskra原理见:https://www.youtube.com/watch?v=NLp9C7AvJhk&t=524s

维基百科:https://zh.wikipedia.org/zh/%E6%88%B4%E5%85%8B%E6%96%AF%E7%89%B9%E6%8B%89%E7%AE%97%E6%B3%95

代码

[code lang=”cpp”]
typedef pair<int, int> pii;

class Solution {
public:
int networkDelayTime(vector<vector<int>>& times, int N, int K) {
vector<vector<pii>> nodes(N + 1, vector<pii>{});
for (auto time : times) {
nodes[time[0]].push_back(make_pair(time[1], time[2]));
}
// declare vars
priority_queue<pii, vector<pii>, greater<pii> > pq; // pii 0 for city index, 1 for cost time
pq.push(make_pair(K, 0));
vector<int> time(N + 1, INT_MAX);
time[K] = 0;
while (!pq.empty()) {
pii node = pq.top();
pq.pop();
// update the time for the sub-nodes
for (auto snode : nodes[node.first]) {
if (time[snode.first] > time[node.first] + snode.second) {
time[snode.first] = time[node.first] + snode.second;
// add the valid sub-node to priority_queue
pq.push(make_pair(snode.first, time[snode.first]));
}
}
}
int a = -1;
for (int i = 1; i < time.size(); ++i) {
if (a < time[i]) a = time[i];
}
return a == INT_MAX ? -1 : a;
}
};
[/code]

复杂度分析

E代表times的长度
时间复杂度:O(ElogE)
空间复杂度:O(E + N)


原题:https://leetcode.com/problems/network-delay-time/
文章来源:胡小旭 => [LeetCode]743. Network Delay Time

Share:

1 Comment

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.