Skip to content

Instantly share code, notes, and snippets.

@siavashk
Created February 23, 2025 21:18
Show Gist options
  • Save siavashk/fc4b135ba72e814a3feffbfe95a4e17f to your computer and use it in GitHub Desktop.
Save siavashk/fc4b135ba72e814a3feffbfe95a4e17f to your computer and use it in GitHub Desktop.
dijkstra
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