Skip to content

Commit e9efb9b

Browse files
committed
dijkstra template
1 parent 321d6f1 commit e9efb9b

File tree

1 file changed

+34
-0
lines changed

1 file changed

+34
-0
lines changed

Template/Graph/dijkstra.py

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
2+
import heapq
3+
class Solution:
4+
5+
def dijkstra(n: int, graph: list[list]):
6+
7+
starting_node = 0
8+
distances = {node: float('inf') for node in range(n)}
9+
distances[starting_node] = 0
10+
11+
pq = [(0, starting_node)]
12+
13+
while len(pq) > 0:
14+
15+
current_distance, current_node = heapq.heappop(pq)
16+
17+
if current_distance > distances[current_node]:
18+
continue
19+
20+
for neighbor, weight in graph[current_node]:
21+
distance = current_distance + weight
22+
# Only consider this new path if it's better than any path we've
23+
# already found.
24+
if distance < distances[neighbor]:
25+
distances[neighbor] = distance
26+
heapq.heappush(pq, (distance, neighbor))
27+
28+
return distances
29+
30+
31+
n = 3
32+
graph = {0: [(1, 2), (2, 4)], 1: [(0, 2), (2, 1)], 2: [(1, 1), (0, 4)]}
33+
print(Solution.dijkstra(n, graph))
34+

0 commit comments

Comments
 (0)