Last active
February 20, 2023 01:51
-
-
Save nanpuhaha/944c555e951be986d299052f08b2cb71 to your computer and use it in GitHub Desktop.
Coding Test
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 | |
import sys | |
INF = float('inf') # or sys.maxsize | |
def dijkstra(start: int, graph: list) -> list: | |
queue = [] | |
heapq.heappush(queue, (0, start)) | |
shortest_distances = [INF] * len(graph) | |
shortest_distances[start] = 0 | |
while queue: | |
distance, node = heapq.heappop(queue) | |
if shortest_distances[node] < distance: | |
continue | |
for adjacent_distance, adjacent_node in graph[node]: | |
new_distance = distance + adjacent_distance | |
if new_distance < shortest_distances[adjacent_node]: | |
shortest_distances[adjacent_node] = new_distance | |
heapq.heappush(queue, (new_distance, adjacent_node)) | |
return shortest_distances |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment