算法过程:
将结点分成两个集合:已确定最短路长度的点集(记为集合)的和未确定最短路长度的点集(记为集合)。一开始所有的点都属于集合。
初始化,其他点的均为。
然后重复这些操作:
- 从集合中,选取一个最短路长度最小的结点,移到集合中。
- 对那些刚刚被加入集合的结点的所有出边执行松弛操作。
直到集合为空,算法结束。
Time Complexity:
Example 0:
You are given a network of n nodes, labeled from 1 to n. You are also given times, a list of travel times as directed edges times[i] = (ui, vi, wi), where ui is the source node, vi is the target node, and wi is the time it takes for a signal to travel from source to target.
We will send a signal from a given node k. Return the minimum time it takes for all the n nodes to receive the signal. If it is impossible for all the n nodes to receive the signal, return -1.
int networkDelayTime(vector<vector<int>> ×, int n, int k) {
vector<vector<Edge>> g(n + 1);
for (int i = 0; i < times.size(); i++) {
int u = times[i][0], v = times[i][1], w = times[i][2];
g[u].push_back({v, w});
}
vector<int> dist(n + 1, INT_MAX);
vector<bool> visited(n + 1, false);
auto cmp = [](const Edge &a, const Edge &b) { return a.second > b.second;};
priority_queue<Edge, vector<Edge>, decltype(cmp)> pq(cmp);
pq.push({k, 0});
dist[k] = 0;
while (!pq.empty()) {
auto [u, du] = pq.top();
pq.pop();
if (visited[u])
continue;
visited[u] = true;
for (auto &e : g[u]) {
auto [v, w] = e;
if (du + w < dist[v]) {
dist[v] = du + w;
pq.push({v, du + w});
}
}
}
int cnt = 0, maxd = INT_MIN;
for (int i = 1; i <= n; i++) {
if (dist[i] != INT_MAX) {
cnt++;
maxd = max(maxd, dist[i]);
}
}
return cnt == n ? maxd : -1;
}