走迷宫代码
时间: 2023-07-02 12:14:07 浏览: 59
好的,以下是 Python 语言实现的走迷宫代码:
```python
maze = [[0, 1, 0, 0, 0],
[0, 1, 0, 1, 0],
[0, 0, 0, 0, 0],
[0, 1, 1, 1, 0],
[0, 0, 0, 1, 0]]
def solve_maze(maze, start, end):
directions = [(0, 1), (0, -1), (1, 0), (-1, 0)] # 可以走的方向
rows, cols = len(maze), len(maze[0])
visited = [[False for _ in range(cols)] for _ in range(rows)] # 记录是否访问过
path = [] # 记录路径
def dfs(curr):
if curr == end:
path.append(curr)
return True
row, col = curr
visited[row][col] = True
for dr, dc in directions:
nr, nc = row + dr, col + dc
if 0 <= nr < rows and 0 <= nc < cols and not visited[nr][nc] and maze[nr][nc] == 0:
if dfs((nr, nc)):
path.append(curr)
return True
return False
dfs(start)
return path[::-1]
start = (0, 0)
end = (4, 4)
path = solve_maze(maze, start, end)
if path:
print("迷宫路径为:")
for row, col in path:
print(f"({row}, {col})")
else:
print("无法找到迷宫路径。")
```
该代码实现了深度优先搜索算法来找到迷宫的路径,并且输出了路径的坐标。