@@ -19,7 +19,7 @@ def __init__(self):
19
19
20
20
def insert (self , node ):
21
21
"""
22
- Insert a node into the Dijkstra Heap.
22
+ Insert a node into the Dijkstra Heap if the vertex is not already visited .
23
23
24
24
:param node: A Node object.
25
25
:return: None
@@ -30,18 +30,15 @@ def insert(self, node):
30
30
31
31
def pop (self ):
32
32
"""
33
- Pop a node from the Dijkstra Heap, adding it to the visited dict.
33
+ Pop an unvisited node from the Dijkstra Heap, adding it to the visited dict.
34
34
35
35
:return: A Node object
36
36
"""
37
37
38
- while self and self [0 ].vertex in self .visited :
39
- heapq .heappop (self )
40
-
41
- if self :
38
+ while self :
42
39
next_elem = heapq .heappop (self )
43
- self .visited [ next_elem .vertex ] = next_elem
44
- return next_elem
40
+ if self .visited . setdefault ( next_elem .vertex , next_elem ) is next_elem :
41
+ return next_elem
45
42
46
43
def backtrack (self , current ):
47
44
"""
@@ -60,14 +57,17 @@ def a_star_search(neighbors, start, end, heuristic):
60
57
"""
61
58
Calculates the shortest path from start to end.
62
59
63
- :param neighbors: The graph, represented by a function that takes a vertex of a comparable and hashable type V and returns its neighbors.
60
+ The graph is defined implicitly by a pair of functions working on vertices. The vertex representation
61
+ may be any comparable and hashable type such as int, tuple, etc.
62
+
63
+ :param neighbors: A function returning the (possibly directed) neighbors of a vertex, along with their costs.
64
64
65
65
neighbors( from_vertex:V ) : Iterable( (to_vertex:V,edge_cost:float), (to_vertex:V,edge_cost:float), ...)
66
66
67
67
:param start: The starting vertex, as type V.
68
68
:param end: The ending vertex, as type V.
69
69
:param heuristic: Heuristic lower-bound cost function taking arguments ( from_vertex:V, end:V ) and returning float.
70
- :returns: A DijkstraHeap object.
70
+ :returns: A DijkstraHeap object. The shortest path is: `reversed(list(d_heap.backtrack(end)))`.
71
71
72
72
"""
73
73
0 commit comments