Network Delay Time LeetCode solution in Python

1
import heapq
2

3

4
class Solution:
5
def networkDelayTime(self, times: List[List[int]], n: int, k: int) -> int:
6

7
adjlist = [[] for _ in range(n + 1)]
8

9
for src, dst, weight in times:
10
adjlist[src].append((dst, weight))
11

12
visited = [-1] * (n + 1)
13
captured = [-1] * (n + 1)
14

15
priority_queue = [(0, k)]
16

17
nums = 0
18
total_dist = 0
19

20
while priority_queue:
21

22
dst, node = heapq.heappop(priority_queue)
23

24
if captured[node] != -1:
25
continue
26
captured[node] = dst
27

28
nums += 1
29
total_dist = dst
30

31
for nbr, wt in adjlist[node]:
32
if captured[nbr] == -1:
33
heapq.heappush(priority_queue, (captured[node] + wt, nbr))
34
if nums == n:
35
return total_dist
36
else:
37
return -1

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0