-
Notifications
You must be signed in to change notification settings - Fork 46
/
Copy path_743_1.py
44 lines (35 loc) · 916 Bytes
/
_743_1.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
36
37
38
39
40
41
42
43
44
"""
LeetCode 743 - Network Delay Time
SPFA
"""
from collections import OrderedDict
"""
LeetCode 743 - Network Delay Time
Floyed
"""
from collections import deque
class Solution:
def networkDelayTime(self, times, N, K):
"""
:type times: List[List[int]]
:type N: int
:type K: int
:rtype: int
"""
inf = 1 << 29
d = [inf] * N
in_queue = [False] * N
edges = [[] for i in range(N)]
for u, v, w in times:
edges[u - 1].append((v - 1, w))
queue = OrderedDict()
queue[K - 1] = K - 1
d[K - 1] = 0
while len(queue) > 0:
u = queue.popitem()[0]
for v, w in edges[u]:
if d[u] + w < d[v]:
d[v] = d[u] + w
if v not in queue:
queue[v] = v
return max(d) if max(d) < inf else -1