Created
February 23, 2025 21:18
-
-
Save siavashk/fc4b135ba72e814a3feffbfe95a4e17f to your computer and use it in GitHub Desktop.
dijkstra
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 | |
def dijkstra(graph, start): | |
pq = [(0, start)] | |
heapq.heapify(pq) | |
dist = {node: float('inf') for node in graph} | |
dist[start] = 0 | |
prev = {node: None for node in graph} | |
while pq: | |
current_dist, current_node = heapq.heappop(pq) | |
if current_dist > dist[current_node]: | |
continue | |
for neighbor, weight in graph[current_node]: | |
new_dist = current_dist + weight | |
if new_dist < dist[neighbor]: | |
dist[neighbor] = new_dist | |
prev[neighbor] = current_node | |
heapq.heappush(pq, (new_dist, neighbor)) | |
return dist, prev |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment