Skip to content

Instantly share code, notes, and snippets.

@jeb2239
Created November 16, 2020 18:28
Show Gist options
  • Save jeb2239/ec80a5d96486752bc64405d2ad7c144f to your computer and use it in GitHub Desktop.
Save jeb2239/ec80a5d96486752bc64405d2ad7c144f to your computer and use it in GitHub Desktop.
import heapq as hq
import sys
import math
from typing import NamedTuple
class Entry(NamedTuple):
cost:int
node:int
class Solution:
def networkDelayTime(self, times: List[List[int]], N: int, K: int) -> int:
graph={}
for i in range(1,N+1):
graph[i]=[]
for u,v,w in times:
graph[u].append(Entry(w,v))
pq = [Entry(0,K)]
dv = [float('inf')]*N # distance vector
dv[K-1]=0
while pq:
curr_dist,curr_node = hq.heappop(pq)
for weight,endNode in graph[curr_node]:
if dv[endNode-1] > curr_dist + weight:
dv[endNode-1]=curr_dist+weight
hq.heappush(pq,Entry(dv[endNode-1],endNode)) # must add using newly
#discovered weight for ordering, this was an error
if any(math.isinf(dist) for dist in dv):
return -1
return max(dv)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment