743. Network Delay Time
Medium
Input: times = [[2,1,1],[2,3,1],[3,4,1]], n = 4, k = 2
Output: 2Input: times = [[1,2,1]], n = 2, k = 1
Output: 1Input: times = [[1,2,1]], n = 2, k = 2
Output: -1Last updated
Input: times = [[2,1,1],[2,3,1],[3,4,1]], n = 4, k = 2
Output: 2Input: times = [[1,2,1]], n = 2, k = 1
Output: 1Input: times = [[1,2,1]], n = 2, k = 2
Output: -1Last updated
class Solution:
def networkDelayTime(self, times: List[List[int]], n: int, k: int) -> int:
weights = {}
d = defaultdict(list)
for source, destination, weight in times:
d[source].append((destination, weight))
q = [(0,k)]
heapq.heapify(q)
while q:
time, node = heapq.heappop(q)
if node not in weights:
weights[node] = time
for adj, w in d[node]:
heapq.heappush(q, (time + w, adj))
return max(weights.values()) if len(weights) == n else -1