Skip to content

Commit 7e335ad

Browse files
authored
Added dijkstra.py
2 parents 6d8f236 + fe0990f commit 7e335ad

2 files changed

Lines changed: 42 additions & 0 deletions

File tree

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@ A repo for storing Python code and tracking learning progress. All programs are
1212
│ ├── binary_search.py
1313
│ ├── bubble_sort.py
1414
│ ├── dfs.py
15+
│ ├── dijkstra.py
1516
│ ├── heap_sort.py
1617
│ ├── merge_sort.py
1718
│ ├── quicksort.py

algorithms/dijkstra.py

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
import heapq
2+
3+
4+
def dijkstra(graph: dict[str, list[tuple[str, int]]], start: str) -> dict[str, int]:
5+
distances = {start: 0}
6+
queue = [(0, start)]
7+
while queue:
8+
current_distance, current_node = heapq.heappop(queue)
9+
if current_distance > distances[current_node]:
10+
continue
11+
for child, weight in graph[current_node]:
12+
if weight < 0:
13+
raise ValueError("Dijkstra's algorithm does not support negative weights.")
14+
new_distance = current_distance + weight
15+
if child not in distances or new_distance < distances[child]:
16+
distances[child] = new_distance
17+
heapq.heappush(queue, (new_distance, child))
18+
return distances
19+
20+
21+
def main() -> None:
22+
graph = {
23+
"(A)": [("(B)", 4), ("(C)", 2)],
24+
"(B)": [("(C)", 5), ("(D)", 10)],
25+
"(C)": [("(E)", 3)],
26+
"(D)": [],
27+
"(E)": [("(D)", 4)],
28+
}
29+
start = "(A)"
30+
31+
distances = dijkstra(graph, start)
32+
print(f"Shortest distances from {start}:")
33+
for node in graph:
34+
if node in distances:
35+
print(f"- {node}: {distances[node]}")
36+
else:
37+
print(f"- {node}: unreachable")
38+
39+
40+
if __name__ == "__main__":
41+
main()

0 commit comments

Comments
 (0)