Created
March 22, 2017 02:03
-
-
Save anbnyc/f3949ecebd19a4d0e6ba4c2ad93272b8 to your computer and use it in GitHub Desktop.
A* Search Implementation in Python
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def astar(source, target, obstacles): | |
def g(start,neighbor): | |
return 10 if start[0] == neighbor[0] or start[1] == neighbor[1] else 14 | |
def h(start,target): | |
return 10 * (abs(start[0] - target[0]) + abs(start[1] - target[1])) | |
def f(neighbor): | |
previous_g = to_see[current]["g"] | |
next_g = g(current,neighbor) | |
next_h = h(neighbor,target) | |
return { | |
"g": previous_g + next_g, | |
"h": next_h, | |
"f": previous_g + next_g + next_h, | |
"parent": current | |
} | |
def astar_print(node, path=""): | |
if seen[node].get("parent"): | |
return astar_print(seen[node]["parent"], (" -> " + str(node) + path)) | |
else: | |
print(str(node) + path) | |
current = source | |
to_see = dict() | |
seen = dict() | |
to_see.update({ current: { "g": 0, "h": h(current,target), "f": h(current,target) } }) | |
while current[:2] != target[:2]: | |
seen.update({ current: to_see[current] }) | |
nbrs = [(current[0]+i, current[1]+j) for i in [-1,0,1] for j in [-1,0,1]] | |
visit_nbrs = { x: f(x) for x in nbrs if x not in obstacles and x not in seen } | |
del to_see[current] | |
for k,v in visit_nbrs.items(): | |
if to_see.get(k): | |
if v["g"] < to_see[k]["g"]: | |
to_see.update({ k: v }) | |
else: | |
to_see.update({ k: v }) | |
to_see.update(visit_nbrs) | |
current = min(visit_nbrs, key=lambda x: visit_nbrs[x]['f']) | |
seen.update({ current: to_see[current] }) | |
astar_print(target) | |
return seen | |
### TEST CASE ### | |
obstacles = {(2,3),(3,3),(4,3),(0,6),(1,6),(2,6)} | |
astar((2,2), (2,7), obstacles) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment