Skip to content
Merged
Show file tree
Hide file tree
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
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
41 changes: 41 additions & 0 deletions algorithms/dijkstra.py
Original file line number Diff line number Diff line change
@@ -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()
Loading