"""
A* Pathfinding Algorithm for Maze Solving
Uses Manhattan distance as the heuristic function
Visualizes solution with Pillow
"""
import heapq
import time
from typing import List, Tuple, Optional, Set
from PIL import Image, ImageDraw, ImageFont
from dataclasses import dataclass
@dataclass
class SearchStats:
"""Statistics from A* search"""
path_length: int = 0
nodes_explored: int = 0
execution_time: float = 0.0
solution_found: bool = False
class MazeAStar:
"""A* pathfinding algorithm for maze solving"""
def __init__(self, maze: List[List[int]], start: Tuple[int, int],
goal: Tuple[int, int]):
"""
Initialize A* maze solver
Args:
maze: 2D list where 0 = walkable, 1 = wall
start: (row, col) starting position
goal: (row, col) goal position
"""
self.maze = maze
self.start = start
self.goal = goal
self.rows = len(maze)
self.cols = len(maze[0])
self.path = []
self.visited = set()
self.stats = SearchStats()
def manhattan_distance(self, pos1: Tuple[int, int],
pos2: Tuple[int, int]) -> int:
"""
Calculate Manhattan distance (L1 norm) between two positions.
This is an admissible heuristic for grid-based pathfinding:
- Never overestimates the actual cost
- Always provides a lower bound on the remaining distance
Args:
pos1: First position (row, col)
pos2: Second position (row, col)
Returns:
Manhattan distance
"""
return abs(pos1[0] - pos2[0]) + abs(pos1[1] - pos2[1])
def get_neighbors(self, pos: Tuple[int, int]) -> List[Tuple[int, int]]:
"""
Get valid neighboring cells (4-directional movement)
Args:
pos: Current position (row, col)
Returns:
List of valid neighbor positions
"""
row, col = pos
neighbors = []
# 4-directional: up, down, left, right
directions = [(-1, 0), (1, 0), (0, -1), (0, 1)]
for dr, dc in directions:
new_row, new_col = row + dr, col + dc
# Check bounds and if not a wall
if (0 <= new_row < self.rows and
0 <= new_col < self.cols and
self.maze[new_row][new_col] == 0):
neighbors.append((new_row, new_col))
return neighbors
def solve(self) -> Optional[List[Tuple[int, int]]]:
"""
Solve maze using A* algorithm
Algorithm:
1. Maintain open_set of nodes to explore
2. For each node, calculate f = g + h where:
- g = cost from start to current node
- h = heuristic (Manhattan distance to goal)
3. Always expand node with lowest f score
4. Continue until goal is found or no paths remain
Returns:
List of positions forming the path, or None if no solution
"""
# Validate start and goal
if self.maze[self.start[0]][self.start[1]] == 1:
print("Error: Start position is a wall!")
return None
if self.maze[self.goal[0]][self.goal[1]] == 1:
print("Error: Goal position is a wall!")
return None
start_time = time.time()
# Initialize data structures
open_set = []
closed_set = set()
came_from = {}
# g_score: actual cost from start to current node
g_score = {self.start: 0}
# h_score: heuristic estimated cost to goal
h_score = {self.start: self.manhattan_distance(self.start, self.goal)}
# f_score: estimated total cost
f_score = {self.start: h_score[self.start]}
# Priority queue: (f_score, counter, position)
# Counter ensures FIFO for equal f_scores
counter = 0
heapq.heappush(open_set, (f_score[self.start], counter, self.start))
counter += 1
while open_set:
current_f, _, current = heapq.heappop(open_set)
# Goal found!
if current == self.goal:
# Reconstruct path
path = []
node = self.goal
while node in came_from:
path.append(node)
node = came_from[node]
path.append(self.start)
self.path = path[::-1]
# Calculate statistics
self.stats.path_length = len(self.path)
self.stats.nodes_explored = len(self.visited)
self.stats.execution_time = time.time() - start_time
self.stats.solution_found = True
return self.path
# Skip if already processed
if current in closed_set:
continue
closed_set.add(current)
self.visited.add(current)
# Expand neighbors
for neighbor in self.get_neighbors(current):
if neighbor in closed_set:
continue
# Calculate tentative g_score
tentative_g = g_score[current] + 1
# Better path found
if neighbor not in g_score or tentative_g < g_score[neighbor]:
came_from[neighbor] = current
g_score[neighbor] = tentative_g
h_score[neighbor] = self.manhattan_distance(neighbor, self.goal)
f_score[neighbor] = g_score[neighbor] + h_score[neighbor]
heapq.heappush(open_set, (f_score[neighbor], counter, neighbor))
counter += 1
self.stats.execution_time = time.time() - start_time
return None
def visualize(self, cell_size: int = 30, filename: str = "maze_solution.png",
show_visited: bool = True, show_info: bool = True):
"""
Visualize maze and solution with Pillow
Args:
cell_size: Size of each cell in pixels
filename: Output filename
show_visited: Show explored cells in light color
show_info: Display statistics on image
"""
width = self.cols * cell_size
height = self.rows * cell_size
# Add space for info text
info_height = 100 if show_info else 0
total_height = height + info_height
# Create image
img = Image.new('RGB', (width, total_height), color='white')
draw = ImageDraw.Draw(img)
# Draw maze
for row in range(self.rows):
for col in range(self.cols):
x0 = col * cell_size
y0 = row * cell_size
x1 = x0 + cell_size - 1
y1 = y0 + cell_size - 1
if self.maze[row][col] == 1:
# Wall - dark gray/black
draw.rectangle([x0, y0, x1, y1], fill='#333333')
elif show_visited and (row, col) in self.visited and \
(row, col) not in self.path:
# Explored nodes - light blue
draw.rectangle([x0, y0, x1, y1], fill='#E8F4F8')
else:
# Open space - white
draw.rectangle([x0, y0, x1, y1], fill='white',
outline='#CCCCCC', width=1)
# Draw path
if self.path and len(self.path) > 1:
path_pixels = [
(col * cell_size + cell_size // 2, row * cell_size + cell_size // 2)
for row, col in self.path
]
draw.line(path_pixels, fill='#0066FF', width=3)
# Draw start point (green)
if self.path:
start_x = self.start[1] * cell_size + cell_size // 2
start_y = self.start[0] * cell_size + cell_size // 2
margin = cell_size // 3
draw.ellipse(
[start_x - margin, start_y - margin,
start_x + margin, start_y + margin],
fill='#00DD00',
outline='#009900',
width=2
)
# Draw goal point (red)
goal_x = self.goal[1] * cell_size + cell_size // 2
goal_y = self.goal[0] * cell_size + cell_size // 2
draw.ellipse(
[goal_x - margin, goal_y - margin,
goal_x + margin, goal_y + margin],
fill='#FF3333',
outline='#990000',
width=2
)
# Draw info panel
if show_info and self.stats.solution_found:
info_y = height + 10
try:
font = ImageFont.truetype("arial.ttf", 14)
small_font = ImageFont.truetype("arial.ttf", 12)
except:
font = ImageFont.load_default()
small_font = font
info_texts = [
f"Solution Found! | Path Length: {self.stats.path_length}",
f"Nodes Explored: {self.stats.nodes_explored} | " +
f"Time: {self.stats.execution_time:.4f}s"
]
for i, text in enumerate(info_texts):
draw.text((10, info_y + i * 25), text, fill='black', font=font)
img.save(filename)
print(f"✓ Visualization saved to '{filename}'")
return img
class MazeGenerator:
"""Generate various types of mazes"""
@staticmethod
def create_simple_maze() -> List[List[int]]:
"""Simple 10x10 maze"""
return [
[0, 1, 0, 0, 0, 0, 1, 0, 0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staticmethod
def create_open_maze() -> List[List[int]]:
"""Mostly open maze with few walls"""
return [
[0, 0, 0, 0, 1, 0, 0, 0, 0, 0],
[0, 1, 0, 0, 1, 0, 1, 0, 1, 0],
[0, 0, 0, 1, 0, 0, 0, 0, 1, 0],
[0, 1, 0, 0, 0, 1, 0, 1, 0, 0],
[0, 0, 0, 1, 0, 0, 0, 0, 0, 1],
[1, 0, 0, 0, 0, 1, 0, 0, 0, 0],
[0, 0, 1, 0, 0, 0, 0, 1, 0, 0],
[0, 0, 0, 0, 1, 0, 0, 0, 0, 1],
[0, 1, 0, 0, 0, 0, 1, 0, 0, 0],
[0, 0, 0, 1, 0, 0, 0, 0, 0, 0],
]
def print_maze_ascii(maze: List[List[int]], path: Optional[List[Tuple[int, int]]] = None,
start: Optional[Tuple[int, int]] = None,
goal: Optional[Tuple[int, int]] = None):
"""Print ASCII representation of maze"""
display = [row[:] for row in maze]
if path:
for row, col in path:
if (row, col) != start and (row, col) != goal:
display[row][col] = 2
if start:
display[start[0]][start[1]] = 3
if goal:
display[goal[0]][goal[1]] = 4
symbols = {0: '·', 1: '█', 2: '·', 3: 'S', 4: 'G'}
print("\n" + "="*60)
print("MAZE WITH SOLUTION PATH")
print("="*60)
print("S = Start | G = Goal | █ = Wall | · = Path/Open")
print("="*60)
for row in display:
print(' '.join(symbols[cell] for cell in row))
print("="*60 + "\n")
def main():
"""Main function demonstrating A* pathfinding"""
print("\n" + "="*60)
print("A* MAZE SOLVER WITH MANHATTAN DISTANCE HEURISTIC")
print("="*60)
# Test cases
test_cases = [
("Simple Maze", MazeGenerator.create_simple_maze(), (0, 0), (9, 9)),
("Complex Maze", MazeGenerator.create_complex_maze(), (0, 0), (14, 14)),
("Open Maze", MazeGenerator.create_open_maze(), (0, 0), (9, 9)),
]
for test_name, maze, start, goal in test_cases:
print(f"\n{'─'*60}")
print(f"Test: {test_name}")
print(f"Maze size: {len(maze)} x {len(maze[0])}")
print(f"Start: {start}, Goal: {goal}")
print(f"Heuristic: Manhattan Distance")
print(f"{'─'*60}")
# Create solver
solver = MazeAStar(maze, start, goal)
# Solve
path = solver.solve()
if path:
print(f"✓ Solution Found!")
print(f" Path length: {solver.stats.path_length} steps")
print(f" Nodes explored: {solver.stats.nodes_explored}")
print(f" Time: {solver.stats.execution_time:.6f} seconds")
# Print ASCII representation
print_maze_ascii(maze, path, start, goal)
# Visualize
filename = f"maze_{test_name.lower().replace(' ', '_')}.png"
solver.visualize(cell_size=40, filename=filename, show_visited=True)
else:
print("✗ No solution found!")
if __name__ == "__main__":
main()