#743
Network Delay Time
medium· Advanced Graphsruns: 0You are given a network of n nodes labeled 1 to n. You are also given times, where times[i] = [u, v, w] indicates a signal that takes w time to travel from u to v. Given a starting node k, return the minimum time for a signal to reach all n nodes. If impossible, return -1.
sign in to paste and practice your own solution
wpm 0acc 100%time 0:000 / 649
import heapq
from collections import defaultdict
class Solution:
def networkDelayTime(
self, times: list[list[int]], n: int, k: int
) -> int:
graph = defaultdict(list)
for u, v, w in times:
graph[u].append((v, w))
dist = {}
heap = [(0, k)]
while heap:
d, node = heapq.heappop(heap)
if node in dist:
continue
dist[node] = d
for neighbor, w in graph[node]:
if neighbor not in dist:
heapq.heappush(heap, (d + w, neighbor))
return max(dist.values()) if len(dist) == n else -1
click the box to focus · tab inserts 4 spaces · backspace to correct · esc to pause
desktop only
codedrill is a typing game and needs a real keyboard. open this on a laptop or desktop to practice.
you can still browse problems and sections from your phone.