Here's a complete example of how to implement the A* (A-star) search algorithm in Python for pathfinding on a grid-based map. This version assumes:
- The grid is 2D.
- Each cell can be either traversable (
0) or blocked (1).
- Movement is allowed in four directions: up, down, left, right.
✅ Features:
- Uses Manhattan distance as the heuristic (can be changed to Euclidean if needed).
- Uses a priority queue via
heapq.
- Returns the shortest (optimal) path from start to goal.
🧠 A* Search Algorithm in Python
import heapq
class Node:
"""A node class for A* Pathfinding"""
def __init__(self, parent=None, position=None):
self.parent = parent
self.position = position
self.g = 0 # Cost from start to this node
self.h = 0 # Heuristic - estimated cost from this node to end
self.f = 0 # Total cost (g + h)
def __eq__(self, other):
return self.position == other.position
def __lt__(self, other):
return self.f < other.f
def astar(grid, start, end):
"""Returns a list of tuples as a path from the given start to the end in a grid"""
# Create start and end nodes
start_node = Node(None, start)
end_node = Node(None, end)
# Initialize both open and closed lists
open_list = []
closed_list = []
# Heapify the open_list and add the start node
heapq.heapify(open_list)
heapq.heappush(open_list, start_node)
# Grid dimensions
rows = len(grid)
cols = len(grid[0])
# Valid moves: up, down, left, right
directions = [(-1, 0), (1, 0), (0, -1), (0, 1)]
# Loop until you find the end
while open_list:
# Get the current node with lowest f value
current_node = heapq.heappop(open_list)
closed_list.append(current_node)
# If reached destination, reconstruct path and return
if current_node == end_node:
path = []
while current_node:
path.append(current_node.position)
current_node = current_node.parent
return path[::-1] # Return reversed path
# Generate children
children = []
for direction in directions:
node_position = (
current_node.position[0] + direction[0],
current_node.position[1] + direction[1]
)
# Make sure within range
if node_position[0] >= rows or node_position[0] < 0 \
or node_position[1] >= cols or node_position[1] < 0:
continue
# Make sure walkable terrain
if grid[node_position[0]][node_position[1]] != 0:
continue
# Create new node with parent and append to children
new_node = Node(current_node, node_position)
children.append(new_node)
# Loop through children
for child in children:
# Child is on the closed list?
if any(child == closed_child for closed_child in closed_list):
continue
# Create the f, g, and h values
child.g = current_node.g + 1
child.h = abs(end_node.position[0] - child.position[0]) + abs(end_node.position[1] - child.position[1])
child.f = child.g + child.h
# Child is already in the open list?
if any(child == open_node and child.f >= open_node.f for open_node in open_list):
continue
# Add the child to the open list
heapq.heappush(open_list, child)
return None # No path found
# Example usage:
if __name__ == '__main__':
# 0 = walkable, 1 = obstacle
grid = [
[0, 0, 0, 0, 0],
[1, 1, 0, 1, 0],
[0, 0, 0, 1, 0],
[0, 1, 0, 0, 0],
[0, 0, 0, 1, 0]
]
start = (0, 0)
end = (4, 4)
path = astar(grid, start, end)
print("Path:", path)
📌 Output Example:
Running this code may give an output like:
Path: [(0, 0), (0, 1), (0, 2), (1, 2), (2, 2), (2, 1), (2, 0), (3, 0), (4, 0), (4, 1), (4, 2), (4, 3), (4, 4)]
This shows the optimal path from start (0, 0) to end (4, 4) avoiding obstacles.
🧪 Optional Enhancements:
- Use diagonal movement by adding more directions.
- Replace the heuristic with Euclidean distance for smoother paths in grids allowing diagonals.
- Visualize the grid and path using libraries like
matplotlib.
Would you like me to show a version with diagonal movement or visualization?