迷宫代码
时间: 2023-07-02 16:13:40 浏览: 50
好的,以下是一个简单的迷宫生成和寻路的 Python 代码:
迷宫生成:
```python
import random
def generate_maze(rows, cols):
maze = [[0 for j in range(cols)] for i in range(rows)]
start_row = random.randint(0, rows-1)
start_col = random.randint(0, cols-1)
maze[start_row][start_col] = 1
stack = [(start_row, start_col)]
while stack:
current_row, current_col = stack.pop()
directions = [(0, 1), (1, 0), (0, -1), (-1, 0)]
random.shuffle(directions)
for d_row, d_col in directions:
new_row, new_col = current_row + 2*d_row, current_col + 2*d_col
if 0 <= new_row < rows and 0 <= new_col < cols and maze[new_row][new_col] == 0:
maze[current_row+d_row][current_col+d_col] = 1
maze[new_row][new_col] = 1
stack.append((new_row, new_col))
return maze
```
寻路:
```python
def find_path(maze, start, end):
rows, cols = len(maze), len(maze[0])
visited = [[False for j in range(cols)] for i in range(rows)]
queue = [start]
while queue:
current_row, current_col = queue.pop(0)
if (current_row, current_col) == end:
return True
visited[current_row][current_col] = True
directions = [(0, 1), (1, 0), (0, -1), (-1, 0)]
for d_row, d_col in directions:
new_row, new_col = current_row + d_row, current_col + d_col
if 0 <= new_row < rows and 0 <= new_col < cols and not visited[new_row][new_col] and maze[new_row][new_col] == 1:
queue.append((new_row, new_col))
return False
```
使用方法:
```python
maze = generate_maze(10, 10)
print(maze)
print(find_path(maze, (0, 0), (9, 9)))
```
其中 `(0, 0)` 和 `(9, 9)` 分别表示起点和终点。