首页 > Web开发 > 详细

leetcode743 Network Delay Time

时间:2020-02-16 21:31:23      阅读:77      评论:0      收藏:0      [点我收藏+]
 1 """
 2 here are N network nodes, labelled 1 to N.
 3 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.
 4 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.
 5 Example 1:
 6 Input: times = [[2,1,1],[2,3,1],[3,4,1]], N = 4, K = 2
 7 Output: 2
 8 """
 9 """
10 此题很经典,是求源点到目标结点的最短路径
11 Dijkstra算法,纯模板题。
12 时间复杂度是O(N^2 + E),空间复杂度是O(N+E).
13 """
14 class Solution1:
15     def networkDelayTime(self, times, N, K):
16         """
17         :type times: List[List[int]]
18         :type N: int
19         :type K: int
20         :rtype: int
21         """
22         dist = [float(inf)] * N
23         dist[K - 1] = 0  #K-1是存到距离数组的下标
24         for i in range(N):  #N个结点,遍历N遍更新最短路径
25             for time in times:
26                 u = time[0] - 1 #减1是为了dist的下标一致
27                 v = time[1] - 1
28                 w = time[2]
29                 dist[v] = min(dist[v], dist[u] + w) #更新最短路径
30         return -1 if float(inf) in dist else max(dist)
31 
32 ss = Solution1()
33 ss.networkDelayTime([[1, 2, 1], [2, 3, 7], [1, 3, 4], [2, 1, 2]], 3, 2)

 

leetcode743 Network Delay Time

原文:https://www.cnblogs.com/yawenw/p/12317969.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!