Solve a maze with A* search using Manhattan distance as the heuristic. Represent the maze as a grid and output the path visually by drawing the solution line on the maze image with Pillow.
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Providing complete A maze solver with Pillow visualization*
The code defines a sample maze grid, implements A* search with Manhattan heuristic, computes a path from start to goal, and draws the maze with walls, start, goal, and the solution path overlaid in red on an image saved as "maze_solution.png".
python
from PIL import Image, ImageDraw
import heapq
# Define a simple maze as a grid: 1 = free, 0 = wall
maze = [
[1, 1, 1, 1, 1, 1, 1],
[1, 0, 0, 0, 1, 0, 1],
[1, 1, 1, 0, 1, 0, 1],
[0, 0, 1, 0, 1, 1, 1],
[1, 1, 1, 0, 0, 0, 1],
[1, 0, 1, 1, 1, 1, 1],
[1, 1, 1, 0, 0, 1, 1]
]
start = (0, 0) # (row, col)
goal = (6, 6) # (row, col)
def manhattan(a, b):
"""Manhattan distance heuristic."""
return abs(a[0] - b[0]) + abs(a[1] - b[1])
def astar(grid, start, goal):
rows, cols = len(grid), len(grid[0])
open_heap = []
heapq.heappush(open_heap, (manhattan(start, goal), 0, start))
came_from = {}
g_score = {start: 0}
closed = set()
while open_heap:
f, g, current = heapq.heappop(open_heap)
if current == goal:
# reconstruct path
path = [current]
while current in came_from:
current = came_from[current]
path.append(current)
path.reverse()
return path
if current in closed:
continue
closed.add(current)
# explore neighbors
for dx, dy in [(1,0), (-1,0), (0,1), (0,-1)]:
nr, nc = current[0] + dx, current[1] + dy
neighbor = (nr, nc)
if not (0 <= nr < rows and 0 <= nc < cols):
continue
if grid[nr][nc] == 0:
continue # wall
tentative_g = g + 1
if tentative_g < g_score.get(neighbor, float('inf')):
came_from[neighbor] = current
g_score[neighbor] = tentative_g
f_score = tentative_g + manhattan(neighbor, goal)
heapq.heappush(open_heap, (f_score, tentative_g, neighbor))
return None # no path
path = astar(maze, start, goal)
print("Path:", path)
# Draw the maze and the path
cell_size = 40
rows, cols = len(maze), len(maze[0])
img = Image.new('RGB', (cols * cell_size, rows * cell_size), color='white')
draw = ImageDraw.Draw(img)
# Draw walls and free spaces
for r in range(rows):
for c in range(cols):
x0, y0 = c * cell_size, r * cell_size
x1, y1 = x0 + cell_size, y0 + cell_size
if maze[r][c] == 0:
draw.rectangle([x0, y0, x1, y1], fill='black')
else:
draw.rectangle([x0, y0, x1, y1], fill='white', outline='gray')
# Draw start and goal
sx0, sy0 = start[1] * cell_size, start[0] * cell_size
gx0, gy0 = goal[1] * cell_size, goal[0] * cell_size
draw.rectangle([sx0, sy0, sx0 + cell_size, sy0 + cell_size], fill='green')
draw.rectangle([gx0, gy0, gx0 + cell_size, gy0 + cell_size], fill='blue')
# Draw path if found
if path:
pts = []
for r, c in path:
# center of the cell
x = c * cell_size + cell_size / 2
y = r * cell_size + cell_size / 2
pts.append((x, y))
draw.line(pts, fill='red', width=3)
img.save('maze_solution.png')
img.show()
This script defines a 7×7 maze grid, runs A* search with the Manhattan distance heuristic to find a path from the top-left corner to the bottom-right corner, and uses Pillow to render the maze. Walls are black, free cells are white with gray outlines, the start cell is green, the goal cell is blue, and the solution path is drawn as a red line connecting the centers of the traversed cells. Running the script will save and display maze_solution.png with the overlaid solution.