原题
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 have1 <= u, v <= N
and1 <= 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
代码
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) {
//cout<<"i:"<<i<<"time:"<<time[i]<<endl;
if (a < time[i]) a = time[i];
}
return a == INT_MAX ? -1 : a;
}
};
复杂度分析
E代表times的长度
时间复杂度:O(ElogE)
空间复杂度:O(E + N)
原题:https://leetcode.com/problems/network-delay-time/
文章来源:胡小旭 => [LeetCode]743. Network Delay Time
人生如白驹过隙,每天浏览几篇博客,学习学习,充实自己!