Here's a complete implementation of the A* search algorithm for grid-based pathfinding in Python:
python
import heapq
from typing import List, Tuple, Optional, Set
import math
class Node:
"""Represents a node in the grid with position and cost information."""
def __init__(self, position: Tuple[int, int], g_cost: float = float('inf'),
h_cost: float = 0, parent: Optional['Node'] = None):
self.position = position
self.g_cost = g_cost # Cost from start to this node
self.h_cost = h_cost # Heuristic cost from this node to goal
self.f_cost = g_cost + h_cost # Total cost
self.parent = parent
def __lt__(self, other):
"""For priority queue comparison."""
return self.f_cost < other.f_cost
def __eq__(self, other):
"""Check if two nodes have the same position."""
return self.position == other.position
class AStarPathfinder:
"""A* pathfinding algorithm implementation for grid-based maps."""
def __init__(self, grid: List[List[int]]):
"""
Initialize the pathfinder with a grid.
Args:
grid: 2D list where 0 represents walkable cells and 1 represents obstacles
"""
self.grid = grid
self.rows = len(grid)
self.cols = len(grid[0]) if self.rows > 0 else 0
def is_valid_position(self, position: Tuple[int, int]) -> bool:
"""Check if a position is within bounds and walkable."""
row, col = position
return (0 <= row < self.rows and
0 <= col < self.cols and
self.grid[row][col] == 0)
def get_neighbors(self, position: Tuple[int, int],
allow_diagonal: bool = True) -> List[Tuple[int, int]]:
"""Get valid neighboring positions."""
row, col = position
neighbors = []
# Cardinal directions (up, right, down, left)
directions = [(0, 1), (1, 0), (0, -1), (-1, 0)]
# Diagonal directions
if allow_diagonal:
directions.extend([(1, 1), (1, -1), (-1, 1), (-1, -1)])
for dr, dc in directions:
new_row, new_col = row + dr, col + dc
new_pos = (new_row, new_col)
if self.is_valid_position(new_pos):
# For diagonal movement, check if path is not blocked
if allow_diagonal and abs(dr) + abs(dc) == 2:
# Check if diagonal path is clear
if (self.is_valid_position((row + dr, col)) and
self.is_valid_position((row, col + dc))):
neighbors.append(new_pos)
else:
neighbors.append(new_pos)
return neighbors
def heuristic(self, pos1: Tuple[int, int], pos2: Tuple[int, int],
method: str = 'manhattan') -> float:
"""
Calculate heuristic distance between two positions.
Args:
pos1: First position
pos2: Second position
method: 'manhattan', 'euclidean', or 'diagonal'
"""
x1, y1 = pos1
x2, y2 = pos2
if method == 'manhattan':
return abs(x1 - x2) + abs(y1 - y2)
elif method == 'euclidean':
return math.sqrt((x1 - x2)**2 + (y1 - y2)**2)
elif method == 'diagonal':
dx = abs(x1 - x2)
dy = abs(y1 - y2)
return max(dx, dy) + (math.sqrt(2) - 1) * min(dx, dy)
else:
raise ValueError(f"Unknown heuristic method: {method}")
def reconstruct_path(self, node: Node) -> List[Tuple[int, int]]:
"""Reconstruct the path from start to goal."""
path = []
current = node
while current:
path.append(current.position)
current = current.parent
return path[::-1] # Reverse to get path from start to goal
def find_path(self, start: Tuple[int, int], goal: Tuple[int, int],
allow_diagonal: bool = True,
heuristic_method: str = 'manhattan') -> Optional[List[Tuple[int, int]]]:
"""
Find the optimal path from start to goal using A* algorithm.
Args:
start: Starting position (row, col)
goal: Goal position (row, col)
allow_diagonal: Whether to allow diagonal movement
heuristic_method: Heuristic calculation method
Returns:
List of positions representing the path, or None if no path exists
"""
if not self.is_valid_position(start) or not self.is_valid_position(goal):
return None
# Initialize start node
start_node = Node(start, g_cost=0,
h_cost=self.heuristic(start, goal, heuristic_method))
# Priority queue of nodes to explore
open_set = [start_node]
heapq.heapify(open_set)
# Set of explored positions
closed_set: Set[Tuple[int, int]] = set()
# Dictionary to track best g_cost for each position
g_costs = {start: 0}
while open_set:
current = heapq.heappop(open_set)
# Check if we reached the goal
if current.position == goal:
return self.reconstruct_path(current)
closed_set.add(current.position)
# Explore neighbors
for neighbor_pos in self.get_neighbors(current.position, allow_diagonal):
if neighbor_pos in closed_set:
continue
# Calculate movement cost (1 for cardinal, sqrt(2) for diagonal)
move_cost = math.sqrt(2) if (
abs(neighbor_pos[0] - current.position[0]) +
abs(neighbor_pos[1] - current.position[1]) == 2
) else 1
tentative_g_cost = current.g_cost + move_cost
# Check if this path to neighbor is better
if neighbor_pos not in g_costs or tentative_g_cost < g_costs[neighbor_pos]:
g_costs[neighbor_pos] = tentative_g_cost
h_cost = self.heuristic(neighbor_pos, goal, heuristic_method)
neighbor_node = Node(neighbor_pos, tentative_g_cost, h_cost, current)
heapq.heappush(open_set, neighbor_node)
return None # No path found
# Example usage and visualization
def visualize_path(grid: List[List[int]], path: Optional[List[Tuple[int, int]]],
start: Tuple[int, int], goal: Tuple[int, int]) -> None:
"""Visualize the grid with the found path."""
if not path:
print("No path found!")
return
# Create a copy of the grid for visualization
visual_grid = [row[:] for row in grid]
# Mark the path
for position in path:
if position != start and position != goal:
visual_grid[position[0]][position[1]] = 2
# Mark start and goal
visual_grid[start[0]][start[1]] = 3
visual_grid[goal[0]][goal[1]] = 4
# Print the grid
symbols = {0: '·', 1: '█', 2: '*', 3: 'S', 4: 'G'}
print("\nPath visualization:")
for row in visual_grid:
print(' '.join(symbols[cell] for cell in row))
print(f"\nPath length: {len(path) - 1} steps")
print(f"Path: {' -> '.join(str(pos) for pos in path)}")
# Example: Create a sample grid and find a path
if __name__ == "__main__":
# Create a sample grid (0 = walkable, 1 = obstacle)
sample_grid = [
[0, 0, 0, 0, 0, 0, 0, 0],
[0, 1, 1, 0, 1, 1, 1, 0],
[0, 0, 0, 0, 0, 0, 0, 0],
[0, 1, 0, 1, 1, 1, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0],
[0, 1, 1, 1, 0, 1, 1, 0],
[0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0]
]
# Initialize pathfinder
pathfinder = AStarPathfinder(sample_grid)
# Define start and goal positions
start_pos = (0, 0)
goal_pos = (7, 7)
# Find path with different configurations
print("A* Pathfinding Examples:")
print("=" * 50)
# Example 1: With diagonal movement
path = pathfinder.find_path(start_pos, goal_pos, allow_diagonal=True)
print("\n1. With diagonal movement (Manhattan heuristic):")
visualize_path(sample_grid, path, start_pos, goal_pos)
# Example 2: Without diagonal movement
path = pathfinder.find_path(start_pos, goal_pos, allow_diagonal=False)
print("\n2. Without diagonal movement (Manhattan heuristic):")
visualize_path(sample_grid, path, start_pos, goal_pos)
# Example 3: With Euclidean heuristic
path = pathfinder.find_path(start_pos, goal_pos, allow_diagonal=True,
heuristic_method='euclidean')
print("\n3. With diagonal movement (Euclidean heuristic):")
visualize_path(sample_grid, path, start_pos, goal_pos)
This implementation includes:
Key Features:
Complete A* algorithm with proper cost calculations
Support for both cardinal (4-directional) and diagonal (8-directional) movement
Multiple heuristic options (Manhattan, Euclidean, and Diagonal distance)
Proper handling of diagonal movement costs (√2 for diagonal moves)
Path reconstruction from goal to start
Efficient priority queue implementation using heapq
Components:
Node class: Represents grid positions with their associated costs
AStarPathfinder class: Main algorithm implementation
find_path(): Core A* search method
visualize_path(): Helper function to display the found path
Usage:
The code includes examples showing how to use the pathfinder with different configurations. You can easily adapt it for your specific needs by:
Modifying the grid representation (e.g., different cost values for terrain)
Adjusting the heuristic function
Adding additional movement constraints
Integrating with game engines or robotics frameworks
The algorithm guarantees finding the optimal path if one exists, making it perfect for pathfinding applications in games, robotics, or navigation systems.