743. Network Delay Time
Dijkstra's algorithm
class Solution:
def networkDelayTime(self, times: List[List[int]], n: int, k: int) -> int:
adj = defaultdict(list)
for u, v, w in times:
adj[u].append((v, w))
t = 0
minH = [(0, k)]
visited = set()
while minH and len(visited) < n:
w1, n1 = heapq.heappop(minH)
if n1 in visited:
continue
visited.add(n1)
t = max(t, w1)
for n2, w2 in adj[n1]:
if n2 not in visited:
heapq.heappush(minH, (w2 + w1, n2))
return t if len(visited) == n else -1