生成一个100x100的数字矩阵迷宫
时间: 2023-11-28 21:48:51 浏览: 64
好的,以下是生成一个100x100的数字矩阵迷宫的 Python 代码:
```python
import random
# 定义迷宫的长和宽
width = 100
height = 100
# 初始化迷宫矩阵
maze = [[1 for j in range(width)] for i in range(height)]
# 随机选择一个起点
start_x = random.randint(0, width - 1)
start_y = random.randint(0, height - 1)
# 将起点标记为通路
maze[start_y][start_x] = 0
# 随机选择一个终点
end_x = random.randint(0, width - 1)
end_y = random.randint(0, height - 1)
# 确保终点和起点不在同一个位置
while end_x == start_x and end_y == start_y:
end_x = random.randint(0, width - 1)
end_y = random.randint(0, height - 1)
# 将终点标记为通路
maze[end_y][end_x] = 0
# 生成迷宫
stack = [(start_x, start_y)]
while stack:
x, y = stack.pop()
directions = [(x-1, y), (x+1, y), (x, y-1), (x, y+1)]
random.shuffle(directions)
for new_x, new_y in directions:
if 0 <= new_x < width and 0 <= new_y < height and maze[new_y][new_x] == 1:
maze[new_y][new_x] = 0
stack.append((new_x, new_y))
# 输出迷宫
for row in maze:
for cell in row:
print(cell, end='')
print()
```
这个程序首先定义了迷宫的长和宽,然后初始化了一个矩阵,用 1 表示墙,用 0 表示通路。程序随机选择起点和终点,并将其标记为通路。接下来,程序使用深度优先搜索算法生成迷宫,最后输出迷宫矩阵。
阅读全文