"""
here 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.
Example 1:
Input: times = [[2,1,1],[2,3,1],[3,4,1]], N = 4, K = 2
Output: 2
"""
"""
此题很经典,是求源点到目标结点的最短路径
Dijkstra算法,纯模板题。
时间复杂度是O(N^2 + E),空间复杂度是O(N+E).
"""
class Solution1:
def networkDelayTime(self, times, N, K):
"""
:type times: List[List[int]]
:type N: int
:type K: int
:rtype: int
"""
dist = [float('inf')] * N
dist[K - 1] = 0 #K-1是存到距离数组的下标
for i in range(N): #N个结点,遍历N遍更新最短路径
for time in times:
u = time[0] - 1 #减1是为了dist的下标一致
v = time[1] - 1
w = time[2]
dist[v] = min(dist[v], dist[u] + w) #更新最短路径
return -1 if float('inf') in dist else max(dist) ss = Solution1()
ss.networkDelayTime([[1, 2, 1], [2, 3, 7], [1, 3, 4], [2, 1, 2]], 3, 2)