Created
November 16, 2020 18:28
-
-
Save jeb2239/ec80a5d96486752bc64405d2ad7c144f to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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