1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
|
import astar
class GraphAStar(astar.AStar):
def __init__(self, nodes):
self.nodes = nodes
def neighbors(self, node):
for n, d in self.nodes[node]:
yield n
# g function
def distance_between(self, n1, n2):
for n, d in self.nodes[n1]:
if n == n2:
return d
# h function
def heuristic_cost_estimate(self, current, goal):
return 1
if __name__ == '__main__':
nodes = {'A': [('B', 100), ('C', 20)],
'C': [('D', 20)],
'D': [('B', 20)]}
# A -> B
graph_solver = GraphAStar(nodes)
print(list(graph_solver.astar('A', 'B')))
print(list(graph_solver.astar('A', 'C')))
|