如何用编程方法生成一个10x10大小的二维迷宫矩阵?
时间: 2024-10-21 08:14:58 浏览: 16
生成一个10x10大小的二维迷宫矩阵通常涉及随机化算法,如深度优先搜索(Depth First Search, DFS)或宽度优先搜索(Width First Search, BFS),再加上一些规则来模拟墙壁和通道。以下是使用Python的一个简单例子,采用DFS算法:
```python
import random
def create_maze(width=10, height=10):
maze = [['#'] * width for _ in range(height)] # 初始化全为墙
visited = [[False] * width for _ in range(height)]
def dfs(x, y):
if x < 0 or x >= width or y < 0 or y >= height or visited[x][y]:
return
visited[x][y] = True
maze[y][x] = ' '
dfs(x + 1, y) # 右
dfs(x - 1, y) # 左
dfs(x, y + 1) # 下
dfs(x, y - 1) # 上
# 随机选择起点
start_x, start_y = random.randint(0, width - 1), random.randint(0, height - 1)
dfs(start_x, start_y)
return maze
maze = create_maze()
for row in maze:
print(' '.join(row))
阅读全文