Created
December 3, 2017 04:31
-
-
Save fogleman/93cca7597d1fcf097a79f1a44f661462 to your computer and use it in GitHub Desktop.
A* Search 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
import heapq | |
def estimated_distance(node, target): | |
x1, y1 = node | |
x2, y2 = target | |
dx, dy = abs(x1 - x2), abs(y1 - y2) | |
dist = dx + dy | |
return dist | |
def shortest_path(graph, source, target, heuristic_func=None): | |
visited = set() | |
queue = [(0, 0, [source])] | |
while queue: | |
_, distance, path = heapq.heappop(queue) | |
node = path[-1] | |
if node == target: | |
return path | |
if node in visited: | |
continue | |
visited.add(node) | |
for neighbor in graph[node]: | |
if neighbor in visited: | |
continue | |
new_path = list(path) | |
new_path.append(neighbor) | |
new_distance = distance + 1 | |
if heuristic_func: | |
estimated_distance = heuristic_func(neighbor, target) | |
else: | |
estimated_distance = 0 | |
new_score = new_distance + estimated_distance | |
heapq.heappush(queue, (new_score, new_distance, new_path)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment