Created
January 29, 2018 08:10
-
-
Save zhuangh/ff971e92b8ecf75329712c41f24da63e to your computer and use it in GitHub Desktop.
Dijkstra python version
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
class Solution: | |
def dijkstra(self, K, N, delay, graph, TIMEOUT): | |
Q = set(range(N)) | |
delay[K-1] = 0 | |
hp = [] | |
heapq.heappush(hp, (0, K-1)) | |
while len(hp) > 0: | |
_, u = heapq.heappop(hp) | |
for v, w in graph[u].items(): | |
if delay[u] + w < delay[v]: | |
delay[v] = delay[u] + w | |
heapq.heappush(hp, (delay[v], v)) | |
d = max(delay) | |
if d == TIMEOUT: | |
d = -1 | |
return d | |
def networkDelayTime(self, times, N, K): | |
""" | |
:type times: List[List[int]] | |
:type N: int | |
:type K: int | |
:rtype: int | |
""" | |
graph = {} | |
delay = [] | |
pre = [] | |
TIME_OUT = 100000 | |
for it in range(N): | |
graph[it] = {} | |
delay.append(TIME_OUT) | |
pre.append(-1) | |
for list_it in times: | |
u, v, w = list_it | |
graph[u-1][v-1] = w | |
return self.dijkstra(K, N, delay, graph, TIME_OUT) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment