PY
py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
import numpy as np
import matplotlib.pyplot as plt
import random
import os
# Function to generate the maze using a recursive backtracking algorithm
def generate_maze(size):
# Create a grid of zeros (walls)
grid = np.zeros((size, size), dtype=int)
# Keep track of visited cells
visited = set()
# Use a stack for backtracking
stack = []
# Helper function to get valid neighbors of a cell
def get_neighbors(x, y):
neighbors = []
# Check up, down, left, and right (2 cells away)
for dx, dy in [(0, 2), (2, 0), (0, -2), (-2, 0)]:
nx, ny = x + dx, y + dy
# Check boundaries and if the cell has been visited
if 0 <= nx < size and 0 <= ny < size and (nx, ny) not in visited:
neighbors.append((nx, ny))
return neighbors
# Recursive function to carve the maze path
def carve_path(x, y):
# Mark the current cell as part of the path
Enter to Rename, Shift+Enter to Preview
OUTPUT
Run