Skip to content

Commit a37c3e6

Browse files
authored
Create Dijkstra’s Algorithm (Shortest Path in Weighted Graph).py
1 parent 788d95b commit a37c3e6

File tree

1 file changed

+31
-0
lines changed

1 file changed

+31
-0
lines changed
Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
import heapq
2+
3+
def dijkstra(graph, start):
4+
distances = {node: float('inf') for node in graph}
5+
distances[start] = 0
6+
pq = [(0, start)]
7+
8+
while pq:
9+
current_distance, current_node = heapq.heappop(pq)
10+
11+
if current_distance > distances[current_node]:
12+
continue
13+
14+
for neighbor, weight in graph[current_node].items():
15+
distance = current_distance + weight
16+
if distance < distances[neighbor]:
17+
distances[neighbor] = distance
18+
heapq.heappush(pq, (distance, neighbor))
19+
20+
return distances
21+
22+
23+
# Example graph (dictionary)
24+
graph = {
25+
'A': {'B': 1, 'C': 4},
26+
'B': {'A': 1, 'C': 2, 'D': 5},
27+
'C': {'A': 4, 'B': 2, 'D': 1},
28+
'D': {'B': 5, 'C': 1}
29+
}
30+
31+
print(dijkstra(graph, 'A'))

0 commit comments

Comments
 (0)