迷宫算法深度算法和广度算法代码
时间: 2024-09-11 12:00:20 浏览: 49
迷宫问题的算法(优于广度优先,深度优.rar_广度优先_广度优先算法_深度优先_迷宫广度优先_迷宫问题
迷宫算法通常分为两类:深度优先搜索(Depth First Search, DFS)和广度优先搜索(Breadth First Search, BFS)。下面是这两种算法的基本概念及简单的伪代码示例:
**深度优先搜索 (DFS)**
DFS是一种递归的思想,从起点开始,尽可能深地探索分支,直到找到出口或无法继续为止。
```python
def dfs(maze, start, end):
stack = [start]
while stack:
current = stack.pop()
if current == end:
return True
for neighbor in maze.neighbors(current):
if neighbor not in visited:
visited.add(neighbor)
stack.append(neighbor)
return False
```
**广度优先搜索 (BFS)**
BFS则是队列驱动的方式,按顺序遍历所有相邻节点,先访问离起点近的节点,再逐步扩大范围。
```python
from collections import deque
def bfs(maze, start, end):
queue = deque([start])
visited = set()
while queue:
current = queue.popleft()
if current == end:
return True
visited.add(current)
for neighbor in maze.neighbors(current):
if neighbor not in visited:
queue.append(neighbor)
return False
```
阅读全文