Faaez Razeen

Network Delay Time

  • 1 min read
  • Graph
  • LC-Medium

3 years ago

Solution

TimeSpaceExplanation
O()O()
def networkDelayTime(self, times: List[List[int]], n: int, k: int) -> int: adj = defaultdict(list) for u, v, w in times: adj[u].append((w, v)) # No need of updating weights if newer distance found since the aim is not to find the global shortest path but immediate shortest path vis = set() q = [(0, k)] while q: time, node = heappop(q) vis.add(node) if len(vis) == n: return time for nbr_time, nbr in adj[node]: if nbr not in vis: heappush(q, (time + nbr_time, nbr)) return -1