Here's an implementation of the A* path-finding algorithm in Python:
main.py
import heapq
classNode:def__init__(self, x, y, reachable): self.x = x
self.y = y
self.reachable = reachable
self.parent = None self.cost = 0 self.heuristic = 0def__lt__(self, other):return self.cost + self.heuristic < other.cost + other.heuristic
defastar(maze, start, end):"""
maze is a list of lists, where each element in the inner list is either 0 or 1,
where 0 is a free cell and 1 is a blocked cell
start is the (x, y) tuple for the starting position
end is the (x, y) tuple for the ending position
""" rows, cols = len(maze), len(maze[0])
closed = [[0] * cols for _ inrange(rows)]
start_node = Node(start[0], start[1], True)
end_node = Node(end[0], end[1], True)
heap = []
heapq.heappush(heap, start_node)
while heap:
curr_node = heapq.heappop(heap)
x, y = curr_node.x, curr_node.y
if curr_node == end_node:
path = []
while curr_node.parent:
path.append((curr_node.x, curr_node.y))
curr_node = curr_node.parent
return path[::-1]
for dx, dy in [(0, 1), (0, -1), (1, 0), (-1, 0)]:
next_x, next_y = x + dx, y + dy
if next_x < 0or next_x >= rows or next_y < 0or next_y >= cols:
continueif closed[next_x][next_y] ornot maze[next_x][next_y]:
continue next_node = Node(next_x, next_y, True)
next_node.parent = curr_node
next_node.cost = curr_node.cost + 1 next_node.heuristic = abs(end_node.x - next_x) + abs(end_node.y - next_y)
heapq.heappush(heap, next_node)
closed[next_x][next_y] = 1returnNone
1821 chars
54 lines
Here's an example usage of the above function with a maze represented as a list of lists: