Skip to content
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
31 changes: 31 additions & 0 deletions Dijkstra’s Algorithm (Shortest Path in Weighted Graph).py
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
import heapq

Check failure on line 1 in Dijkstra’s Algorithm (Shortest Path in Weighted Graph).py

View workflow job for this annotation

GitHub Actions / ruff

Ruff (I001)

Dijkstra’s Algorithm (Shortest Path in Weighted Graph).py:1:1: I001 Import block is un-sorted or un-formatted

def dijkstra(graph, start):
distances = {node: float('inf') for node in graph}
distances[start] = 0
pq = [(0, start)]

while pq:
current_distance, current_node = heapq.heappop(pq)

if current_distance > distances[current_node]:
continue

for neighbor, weight in graph[current_node].items():
distance = current_distance + weight
if distance < distances[neighbor]:
distances[neighbor] = distance
heapq.heappush(pq, (distance, neighbor))

return distances


# Example graph (dictionary)
graph = {
'A': {'B': 1, 'C': 4},
'B': {'A': 1, 'C': 2, 'D': 5},
'C': {'A': 4, 'B': 2, 'D': 1},
'D': {'B': 5, 'C': 1}
}

print(dijkstra(graph, 'A'))
Loading