Skip to content

Instantly share code, notes, and snippets.

@jinwoo1225
Created May 31, 2021 05:47
Show Gist options
  • Save jinwoo1225/43fcdafec6c1aed4f531f2ba98631dbb to your computer and use it in GitHub Desktop.
Save jinwoo1225/43fcdafec6c1aed4f531f2ba98631dbb to your computer and use it in GitHub Desktop.
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