From fe0990fc1ada9fcb4ab21d5070420ec2a1d63363 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Johan=20Wahr=C3=A9us?= Date: Wed, 27 May 2026 20:47:18 +0200 Subject: [PATCH] Added dijkstra.py --- README.md | 1 + algorithms/dijkstra.py | 41 +++++++++++++++++++++++++++++++++++++++++ 2 files changed, 42 insertions(+) create mode 100644 algorithms/dijkstra.py diff --git a/README.md b/README.md index 297ff0b..4b7160f 100644 --- a/README.md +++ b/README.md @@ -12,6 +12,7 @@ A repo for storing Python code and tracking learning progress. All programs are │ ├── binary_search.py │ ├── bubble_sort.py │ ├── dfs.py +│ ├── dijkstra.py │ ├── heap_sort.py │ ├── merge_sort.py │ ├── quicksort.py diff --git a/algorithms/dijkstra.py b/algorithms/dijkstra.py new file mode 100644 index 0000000..5e07234 --- /dev/null +++ b/algorithms/dijkstra.py @@ -0,0 +1,41 @@ +import heapq + + +def dijkstra(graph: dict[str, list[tuple[str, int]]], start: str) -> dict[str, int]: + distances = {start: 0} + queue = [(0, start)] + while queue: + current_distance, current_node = heapq.heappop(queue) + if current_distance > distances[current_node]: + continue + for child, weight in graph[current_node]: + if weight < 0: + raise ValueError("Dijkstra's algorithm does not support negative weights.") + new_distance = current_distance + weight + if child not in distances or new_distance < distances[child]: + distances[child] = new_distance + heapq.heappush(queue, (new_distance, child)) + return distances + + +def main() -> None: + graph = { + "(A)": [("(B)", 4), ("(C)", 2)], + "(B)": [("(C)", 5), ("(D)", 10)], + "(C)": [("(E)", 3)], + "(D)": [], + "(E)": [("(D)", 4)], + } + start = "(A)" + + distances = dijkstra(graph, start) + print(f"Shortest distances from {start}:") + for node in graph: + if node in distances: + print(f"- {node}: {distances[node]}") + else: + print(f"- {node}: unreachable") + + +if __name__ == "__main__": + main() \ No newline at end of file