Created
May 31, 2021 05:47
-
-
Save jinwoo1225/43fcdafec6c1aed4f531f2ba98631dbb to your computer and use it in GitHub Desktop.
This file contains 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 | |
# https://justkode.kr/algorithm/python-dijkstra | |
def dijkstra(graph: dict, start: int) -> dict: | |
distances = {node: float('inf') for node in graph} | |
distances[start] = 0 | |
queue = [] | |
heapq.heappush(queue, [distances[start], start]) | |
while queue: | |
current_distance, current_destination = heapq.heappop(queue) | |
if distances[current_destination] < current_distance: | |
continue | |
for new_destination, new_distance in graph[current_destination].items(): | |
distance = current_distance + new_distance | |
if distance < distances[new_destination]: | |
distances[new_destination] = distance | |
heapq.heappush(queue, [distance, new_destination]) | |
return distances |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment