Skip to content

Instantly share code, notes, and snippets.

@szolotykh
Last active February 25, 2020 19:07
Show Gist options
  • Save szolotykh/eb0d953de555a48067f7 to your computer and use it in GitHub Desktop.
Save szolotykh/eb0d953de555a48067f7 to your computer and use it in GitHub Desktop.
Implementation A* in python
def AStar(problem):
closedset = list()
openset = list()
came_from = dict()
g_score = dict()
f_score = dict()
goal = problem.getGoal()
start = problem.getStart()
g_score[start] = 0
f_score[start] = g_score[start] + problem.getHeuristic(start, goal)
openset.append(start)
while len(openset)>0:
current = openset[0]
for el in openset:
if f_score[el] < f_score[current]:
current = el
print current
if current == goal:
return reconstruct_path(came_from, goal)
openset.remove(current)
closedset.append(current)
problem.expended = problem.expended+1
for neighbor in problem.getNeighbors(current):
if neighbor in closedset:
continue
tentative_g_score = g_score[current] + problem.getDistance(current, neighbor)
if neighbor not in openset or tentative_g_score < g_score[neighbor]:
came_from[neighbor] = current
g_score[neighbor] = tentative_g_score
f_score[neighbor] = g_score[neighbor] + problem.getHeuristic(neighbor, goal)
if neighbor not in openset:
openset.append(neighbor)
return []
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment