Solve problem 81 to 83 in Python and learn A* algorithm along the way.
This commit is contained in:
33
python/lib_a_star.py
Normal file
33
python/lib_a_star.py
Normal file
@@ -0,0 +1,33 @@
|
||||
class A_Star(object):
|
||||
def __init__(self, starts, goals, h, d, neighbors):
|
||||
"""
|
||||
:param h: heuristic function
|
||||
:param d: cost from node to node function
|
||||
:param neighbors: neighbors function
|
||||
"""
|
||||
open_set = []
|
||||
g_score = {}
|
||||
f_score = {}
|
||||
|
||||
for start in starts:
|
||||
open_set.append(start)
|
||||
g_score[start] = d(0, start)
|
||||
f_score[start] = h(start)
|
||||
|
||||
while open_set:
|
||||
open_set.sort(key=lambda node: f_score[node])
|
||||
current = open_set[0]
|
||||
|
||||
if current in goals:
|
||||
self.cost = g_score[current]
|
||||
break
|
||||
|
||||
open_set = open_set[1:] # remove current
|
||||
|
||||
for neighbor in neighbors(current):
|
||||
tentative_g_score = g_score[current] + d(current, neighbor)
|
||||
if neighbor not in g_score or \
|
||||
tentative_g_score < g_score[neighbor]:
|
||||
g_score[neighbor] = tentative_g_score
|
||||
f_score[neighbor] = g_score[neighbor] + h(neighbor)
|
||||
open_set.append(neighbor)
|
||||
Reference in New Issue
Block a user