中级农民
- 积分
- 102
- 大米
- 颗
- 鳄梨
- 个
- 水井
- 尺
- 蓝莓
- 颗
- 萝卜
- 根
- 小米
- 粒
- 学分
- 个
- 注册时间
- 2019-3-4
- 最后登录
- 1970-1-1
|
注册一亩三分地论坛,查看更多干货!
您需要 登录 才可以下载或查看附件。没有帐号?注册账号
x
leetcode: 743 Network Delay Time
我写了两个版本,这个是错的:
- class Solution:
- def networkDelayTime(self, times: List[List[int]], N: int, K: int) -> int:
- graph = collections.defaultdict(list)
- for source, target, time in times:
- graph[source].append((time, target))
- q = []
- heapq.heappush(q, (0, K))
- arrival = {}
- arrival[K] = 0
- while q:
- time, node = heapq.heappop(q)
- for t, n in graph[node]:
- if n not in arrival:
- arrival[n] = time + t
- heapq.heappush(q, (time + t, n))
- res = 0
- if len(arrival) < N:
- return -1
- for i, v in arrival.items():
- res = max(res, v)
- return res
复制代码
这个是对的:
- class Solution:
- def networkDelayTime(self, times: List[List[int]], N: int, K: int) -> int:
- graph = collections.defaultdict(list)
- for source, target, time in times:
- graph[source].append((time, target))
- q = []
- heapq.heappush(q, (0, K))
- arrival = {}
- while q:
- time, node = heapq.heappop(q)
- if node not in arrival:
- arrival[node] = time
- for t, n in graph[node]:
- heapq.heappush(q, (t+ time, n))
- res = 0
- if len(arrival) < N:
- return -1
- for i, v in arrival.items():
- res = max(res, v)
- return res
复制代码
请各位帮忙指出为哈第一个错了?谢谢!
补充内容 (2019-5-14 14:04):
想明白了,第一个更新节点到达的时间太快了,应该交给priority queue延迟更新才能得到最短路径 |
上一篇: 请教一道SQL题,OA遇到了,做不起然后挂了下一篇: 有刷题Tutorial的推荐嘛?
|