-
-
Notifications
You must be signed in to change notification settings - Fork 49.1k
Added Dijkstra's shortest path problem #13822
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: master
Are you sure you want to change the base?
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,88 @@ | ||
| """Dijkstra's shortest path algorithm. | ||
|
|
||
| This module provides a simple Dijkstra implementation that works on a | ||
| graph represented as an adjacency mapping: {node: [(neighbor, weight), ...], ...}. | ||
|
|
||
| Functions: | ||
| - dijkstra(graph, source) -> (dist, prev) | ||
| - shortest_path(prev, target) -> list | ||
|
|
||
| Doctests include a small example graph. | ||
| """ | ||
|
|
||
| from __future__ import annotations | ||
|
|
||
| import heapq | ||
| from typing import Dict, Iterable, List, Tuple, Any | ||
|
Check failure on line 16 in searches/dijkstra.py
|
||
|
|
||
|
|
||
| def dijkstra( | ||
| graph: Dict[Any, Iterable[Tuple[Any, float]]], source: Any | ||
|
Check failure on line 20 in searches/dijkstra.py
|
||
| ) -> Tuple[Dict[Any, float], Dict[Any, Any]]: | ||
|
Check failure on line 21 in searches/dijkstra.py
|
||
| """Compute shortest path distances from source to all reachable nodes. | ||
|
|
||
| Args: | ||
| graph: adjacency mapping where graph[u] yields (v, weight) pairs. | ||
| source: start node. | ||
|
|
||
| Returns: | ||
| (dist, prev) | ||
| - dist: mapping node -> distance (float). Unreachable nodes are absent. | ||
| - prev: mapping node -> predecessor on shortest path (or None for source). | ||
|
|
||
| Example: | ||
| >>> graph = { | ||
| ... 'A': [('B', 1), ('C', 4)], | ||
| ... 'B': [('C', 2), ('D', 5)], | ||
| ... 'C': [('D', 1)], | ||
| ... 'D': [] | ||
| ... } | ||
| >>> dist, prev = dijkstra(graph, 'A') | ||
| >>> dist['D'] | ||
| 4 | ||
| >>> shortest_path(prev, 'D') | ||
| ['A', 'B', 'C', 'D'] | ||
| """ | ||
| dist: Dict[Any, float] = {} | ||
| prev: Dict[Any, Any] = {} | ||
| pq: List[Tuple[float, Any]] = [] # (distance, node) | ||
|
|
||
| heapq.heappush(pq, (0.0, source)) | ||
| dist[source] = 0.0 | ||
| prev[source] = None | ||
|
|
||
| while pq: | ||
| d, u = heapq.heappop(pq) | ||
| # Skip stale entries | ||
| if d != dist.get(u, float("inf")): | ||
| continue | ||
| for v, w in graph.get(u, []): | ||
| nd = d + float(w) | ||
| if nd < dist.get(v, float("inf")): | ||
| dist[v] = nd | ||
| prev[v] = u | ||
| heapq.heappush(pq, (nd, v)) | ||
|
|
||
| return dist, prev | ||
|
|
||
|
|
||
| def shortest_path(prev: Dict[Any, Any], target: Any) -> List[Any]: | ||
| """Reconstruct path from source to target using predecessor map. | ||
|
|
||
| If target is not in `prev`, returns an empty list. | ||
| """ | ||
| if target not in prev: | ||
| return [] | ||
| path: List[Any] = [] | ||
| cur = target | ||
| while cur is not None: | ||
| path.append(cur) | ||
| cur = prev.get(cur) | ||
| path.reverse() | ||
| return path | ||
|
|
||
|
|
||
| if __name__ == "__main__": | ||
| import doctest | ||
|
|
||
| doctest.testmod() | ||
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
As there is no test file in this pull request nor any test function or class in the file
searches/dijkstra.py, please provide doctest for the functionshortest_path