用python代码解决迷宫问题,使用dfs完成所有路径搜索;使用bfs获取最优路径
时间: 2024-05-12 10:16:51 浏览: 99
好的,我知道了。下面是Python代码解决迷宫问题,使用dfs完成所有路径搜索,使用bfs获取最优路径:
```
# 定义迷宫
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]]
# 定义节点结构体
class Node:
def __init__(self, x, y, pre):
self.x = x
self.y = y
self.pre = pre
# 深度优先搜索
def dfs(x, y):
stack = [Node(x, y, None)]
while len(stack) > 0:
cur = stack.pop()
if maze[cur.x][cur.y] == 2:
return cur
# 标记已访问过
maze[cur.x][cur.y] = 1
# 向四个方向查找
if cur.x > 0 and maze[cur.x-1][cur.y] == 0:
stack.append(Node(cur.x-1, cur.y, cur))
if cur.y > 0 and maze[cur.x][cur.y-1] == 0:
stack.append(Node(cur.x, cur.y-1, cur))
if cur.x < len(maze)-1 and maze[cur.x+1][cur.y] == 0:
stack.append(Node(cur.x+1, cur.y, cur))
if cur.y < len(maze[0])-1 and maze[cur.x][cur.y+1] == 0:
stack.append(Node(cur.x, cur.y+1, cur)))
return None # 没有路径
# 广度优先搜索
def bfs(x, y):
queue = [Node(x, y, None)]
while len(queue) > 0:
cur = queue.pop(0)
if maze[cur.x][cur.y] == 2:
return cur
# 标记已访问过
maze[cur.x][cur.y] = 1
# 向四个方向查找
if cur.x > 0 and maze[cur.x-1][cur.y] == 0:
queue.append(Node(cur.x-1, cur.y, cur))
if cur.y > 0 and maze[cur.x][cur.y-1] == 0:
queue.append(Node(cur.x, cur.y-1, cur))
if cur.x < len(maze)-1 and maze[cur.x+1][cur.y] == 0:
queue.append(Node(cur.x+1, cur.y, cur))
if cur.y < len(maze[0])-1 and maze[cur.x][cur.y+1] == 0:
queue.append(Node(cur.x, cur.y+1, cur)))
return None # 没有路径
# 测试
start = (0, 0)
end = (4, 3)
result_dfs = dfs(start[0], start[1])
if result_dfs is not None:
print("dfs找到路径:")
path = []
node = result_dfs
while node is not None:
path.insert(0, (node.x, node.y))
node = node.pre
print(path)
else:
print("dfs没有找到路径")
result_bfs = bfs(start[0], start[1])
if result_bfs is not None:
print("bfs找到路径:")
path = []
node = result_bfs
while node is not None:
path.insert(0, (node.x, node.y))
node = node.pre
print(path)
else:
print("bfs没有找到路径")
```
这段代码会先定义一个迷宫,然后定义一个节点结构体来记录节点信息,接着实现深度优先搜索和广度优先搜索,最后进行测试并输出结果。
阅读全文