原题
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.
leetCode地址:https://leetcode.com/problems/network-delay-time/description/
解题思路
题目大意:有N个网络节点,给出相互连接的线路以及线路耗时;现选择某个节点,向其所有邻居发送信号,且任何节点接收到信号后都会转发出去。求从信号产生开始,到最后一个节点收到信号的最短时间。如果有节点不能收到信号,返回-1。
这个信号的传播类似路由器的工作原理,转发路由表就是这种情况。
要求的是到达最后一个节点的最短时间,很明显我们可以发现,这是一个类似求单源最短路的问题。
先通过给出的边来构建带权图,然后选择一个节点起始,对其余所有节点都求最短路径;求得最大的路径值就是需要的耗时。
求单源最短路的算法有很多,类似Dijkstra算法、Floyd算法等都可以完成,我选择的是Dijkstra算法。