python利用栈和队列写一个迷宫
时间: 2023-10-16 14:08:27 浏览: 84
利用栈和队列实现迷宫
好的,下面是一个利用栈和队列实现迷宫求解的Python代码:
```python
# 迷宫的地图,0表示可以通过,1表示障碍物
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]
]
# 定义方向,(dx, dy)表示向右移动dx格,向下移动dy格
directions = [(0, 1), (1, 0), (0, -1), (-1, 0)]
# 判断点是否在迷宫内
def is_valid(x, y):
return x >= 0 and x < len(maze) and y >= 0 and y < len(maze[0]) and maze[x][y] == 0
# 利用栈求解迷宫,返回路径
def dfs(start, end):
stack = [start]
visited = set()
while stack:
x, y, path = stack.pop()
if (x, y) == end:
return path
for dx, dy in directions:
nx, ny = x + dx, y + dy
if is_valid(nx, ny) and (nx, ny) not in visited:
stack.append((nx, ny, path + [(nx, ny)]))
visited.add((nx, ny))
return None
# 利用队列求解迷宫,返回路径
def bfs(start, end):
queue = [(start, [start])]
visited = set([start])
while queue:
(x, y), path = queue.pop(0)
if (x, y) == end:
return path
for dx, dy in directions:
nx, ny = x + dx, y + dy
if is_valid(nx, ny) and (nx, ny) not in visited:
queue.append(((nx, ny), path + [(nx, ny)]))
visited.add((nx, ny))
return None
# 测试
start = (0, 0)
end = (4, 4)
print(dfs(start, end))
print(bfs(start, end))
```
该代码定义了一个5×5的迷宫地图,0表示可以通过,1表示障碍物。利用栈和队列分别实现了深度优先搜索和广度优先搜索,求解从起点到终点的路径。在测试中,起点为(0, 0),终点为(4, 4),输出结果均为[(0, 0), (1, 0), (2, 0), (2, 1), (2, 2), (3, 2), (4, 2), (4, 3), (4, 4)],即从起点到终点的路径。
阅读全文