Problem
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 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.
Constraints:
- 1 <= k <= n <= 100
- 1 <= times.length <= 6000
- times[i].length == 3
- 1 <= ui, vi <= n
- ui != vi
- 0 <= wi <= 100
- All the pairs (ui, vi) are unique. (i.e., no multiple edges.)
Example1
Input: times = [[2,1,1],[2,3,1],[3,4,1]], n = 4, k = 2
Output: 2
Example2
Input: times = [[1,2,1]], n = 2, k = 1
Output: 1
Example3
Input: times = [[1,2,1]], n = 2, k = 2
Output: -1
Solution
class Solution {
public:
int networkDelayTime(vector<vector<int>> ×, int n, int k) {
const int inf = INT_MAX / 2;
// 邻接矩阵存储边信息
vector<vector<int>> g(n, vector<int>(n, inf));
for (auto &t : times) {
// 边序号从 0 开始
int x = t[0] - 1, y = t[1] - 1;
g[x][y] = t[2];
}
// 从源点到某点的距离数组
vector<int> dist(n, inf);
// 由于从 k 开始,所以该点距离设为 0,也即源点
dist[k - 1] = 0;
// 节点是否被更新数组
vector<bool> used(n);
for (int i = 0; i < n; ++i) {
// 在还未确定最短路的点中,寻找距离最小的点
int x = -1;
for (int y = 0; y < n; ++y) {
if (!used[y] && (x == -1 || dist[y] < dist[x])) {
x = y;
}
}
// 用该点更新所有其他点的距离
used[x] = true;
for (int y = 0; y < n; ++y) {
dist[y] = min(dist[y], dist[x] + g[x][y]);
}
}
// 找到距离最远的点
int ans = *max_element(dist.begin(), dist.end());
return ans == inf ? -1 : ans;
}
};