Jul 10, 2024
n nodes labeled from 1 to n and a list of times representing directed edges with weights.k, determine the time required for a signal to reach all nodes.-1 if not all nodes can be reached.times list of triples (u, v, w) where u is the source node, v is the target node, and w is the weight.k is the starting point node.2 (k=2).2, 1: Time = 13, 4: Time = 2 (1+1)0.t for result.t.t.-1.k with path length 0.visit to keep track of visited nodes.t to 0.t if all nodes are visited; otherwise return -1.import heapq
def networkDelayTime(times, n, k):
edges = {i: [] for i in range(1, n + 1)}
for u, v, w in times:
edges[u].append((v, w))
min_heap = [(0, k)]
visit = set()
t = 0
while min_heap:
w1, n1 = heapq.heappop(min_heap)
if n1 in visit:
continue
visit.add(n1)
t = max(t, w1)
for n2, w2 in edges[n1]:
if n2 not in visit:
heapq.heappush(min_heap, (w1 + w2, n2))
return t if len(visit) == n else -1