题目
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.
分析
这道题可以简化为有向图求某一点到其余点最短路径的问题,因为网络传播时,信号向所有方向传播,某节点收到信号时,该信号一定是经过最短的路径到达的。若从起始点出发,存在一点与起始点不连通,则返回-1,否则返回起始点到其余点最短路径中的最大值。
因为题目中边的权都是正数,所以这里使用Dijkstra算法,大概思路如下:
- 一开始设置从起始点到其余点 i 的最短路径 dist[i] 为 INT_MAX
- 以宽度优先算法遍历有向图,遍历到的节点 u ,查看与 u 相连的所有节点 v,若 dist[u] + l(u,v) < dist[v],则令dist[v] = dist[u] + l(u,v)。
- 最后检查所有节点 i 的 dist[i],若存在 dist[i] 为 INT_MAX,说明有节点与初始点不连通,返回 -1,否则返回 dist[i] 中的最大值。
代码
1 |
|