Sure! Below is a Python program that generates a medium-sized maze, solves it using the Depth-First Search (DFS) algorithm, and visualizes both the maze and the solution path using Matplotlib.
import random
import matplotlib.pyplot as plt
# Maze generation using Recursive Backtracking
class Maze:
def __init__(self, width=20, height=20):
self.width = width
self.height = height
self.maze = [[0]*width for _ in range(height)]
self.visited = [[False]*width for _ in range(height)]
self.dirs = [(-1, 0), (0, 1), (1, 0), (0, -1)]
def generate(self, x=0, y=0):
self.visited[y][x] = True
dir_order = self.dirs[:]
random.shuffle(dir_order)
for dx, dy in dir_order:
nx, ny = x + dx, y + dy
if (0 <= nx < self.width and 0 <= ny < self.height and not self.visited[ny][nx]):
self.maze[y][x] |= self.direction_to_bit(dx, dy)
self.maze[ny][nx] |= self.direction_to_bit(-dx, -dy)
self.generate(nx, ny)
def direction_to_bit(self, dx, dy):
if dx == -1 and dy == 0:
return 1 # Left
elif dx == 1 and dy == 0:
return 2 # Right
elif dx == 0 and dy == -1:
return 4 # Up
elif dx == 0 and dy == 1:
return 8 # Down
return 0
# Maze solver using Depth-First Search
def solve_maze(maze):
width, height = maze.width, maze.height
start = (0, 0)
goal = (width - 1, height - 1)
stack = [start]
came_from = {start: None}
while stack:
current = stack.pop()
if current == goal:
break
x, y = current
for dx, dy in maze.dirs:
nx, ny = x + dx, y + dy
if (0 <= nx < width and 0 <= ny < height):
if can_move(maze, x, y, dx, dy) and (nx, ny) not in came_from:
stack.append((nx, ny))
came_from[(nx, ny)] = (x, y)
# Reconstruct path
path = []
current = goal
while current != start:
path.append(current)
current = came_from[current]
path.append(start)
path.reverse()
return path
def can_move(maze, x, y, dx, dy):
curr_cell = maze.maze[y][x]
if dx == -1 and dy == 0:
return curr_cell & 1 != 0
elif dx == 1 and dy == 0:
return curr_cell & 2 != 0
elif dx == 0 and dy == -1:
return curr_cell & 4 != 0
elif dx == 0 and dy == 1:
return curr_cell & 8 != 0
return False
# Visualization
def draw_maze(maze, path=None):
width, height = maze.width, maze.height
fig, ax = plt.subplots(figsize=(10, 10))
ax.set_aspect('equal')
# Draw walls
for y in range(height):
for x in range(width):
cell = maze.maze[y][x]
# Left wall
if cell & 1 == 0:
ax.plot([x, x], [y, y+1], color='black')
# Right wall
if cell & 2 == 0:
ax.plot([x+1, x+1], [y, y+1], color='black')
# Top wall
if cell & 4 == 0:
ax.plot([x, x+1], [y, y], color='black')
# Bottom wall
if cell & 8 == 0:
ax.plot([x, x+1], [y+1, y+1], color='black')
# Draw path
if path:
px, py = zip(*[(x+0.5, y+0.5) for x, y in path])
ax.plot(px, py, color='red', linewidth=2)
# Start and goal
ax.plot(0.5, 0.5, 'go', markersize=10) # Start
ax.plot(width - 0.5, height - 0.5, 'ro', markersize=10) # Goal
plt.axis('off')
plt.show()
def main():
maze = Maze()
maze.generate()
path = solve_maze(maze)
draw_maze(maze, path)
if __name__ == '__main__':
main()
Explanation:
-
Maze Generation:
- We use a recursive backtracking algorithm to generate the maze.
- Each cell in the maze grid can have walls on its four sides. We represent the walls using bit masking.
- The
Maze class handles maze generation.
-
Maze Solving:
- We implement the Depth-First Search (DFS) algorithm to solve the maze.
- The solver navigates through the maze, keeping track of the path.
- Once the goal is reached, we backtrack to reconstruct the path from start to goal.
-
Visualization:
- We use
matplotlib to draw the maze and the solution path.
- Walls are drawn as black lines, the path as a red line.
- The start and goal positions are marked with green and red dots, respectively.
Requirements:
- Ensure you have
matplotlib installed. You can install it via pip if necessary:
pip install matplotlib
How to Run the Program:
- Copy the code into a file named
maze_solver.py.
- Run the script using Python 3:
python maze_solver.py
- The program will display the maze with the solution path visualized.
Sample Output:
The program will open a window displaying a maze similar to the one below:
[image: Maze with Solution Path] open (Note: Replace with an actual image if possible)
Customization:
Let me know if you have any questions or need further assistance!