forked from kamyu104/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathnetwork-delay-time.py
36 lines (32 loc) · 1.09 KB
/
network-delay-time.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
# Time: O((|E| + |V|) * log|V|) = O(|E| * log|V|) by using binary heap,
# if we can further to use Fibonacci heap, it would be O(|E| + |V| * log|V|)
# Space: O(|E| + |V|) = O(|E|)
import collections
import heapq
# Dijkstra's algorithm
class Solution(object):
def networkDelayTime(self, times, N, K):
"""
:type times: List[List[int]]
:type N: int
:type K: int
:rtype: int
"""
adj = [[] for _ in xrange(N)]
for u, v, w in times:
adj[u-1].append((v-1, w))
result = 0
lookup = set()
best = collections.defaultdict(lambda: float("inf"))
min_heap = [(0, K-1)]
while min_heap and len(lookup) != N:
result, u = heapq.heappop(min_heap)
lookup.add(u)
if best[u] < result:
continue
for v, w in adj[u]:
if v in lookup: continue
if result+w < best[v]:
best[v] = result+w
heapq.heappush(min_heap, (result+w, v))
return result if len(lookup) == N else -1