graph = collections.defaultdict(list)
for idx in range(len(times)):
source, dest, time = times[idx][0], times[idx][1], times[idx][2]
graph[source].append([dest, time])
minHeap = [(0, k)]
delay = 0
visited = set()
while minHeap:
path, node = heapq.heappop(minHeap)
if node in visited:
continue
visited.add(node)
delay = max(delay, path)
for nextNode, nextPath in graph[node]:
if nextNode not in visited:
heapq.heappush(minHeap, (path + nextPath, nextNode))
if len(visited) == n:
return delay
return -1
The following code uses heapq class instead of a priority queue class but essentially implements the same thing