迷宫路径算法多条代码
时间: 2024-09-10 08:18:37 浏览: 50
迷宫路径算法是一种常见的图搜索问题解决方案,通常用于解决从起点到终点在迷宫中找到一条无死路的路径。这里我会简述几种常见的迷宫路径算法及其示例代码:
1. **深度优先搜索 (DFS)**
```python
def dfs(maze, start, end):
stack = [start]
visited = set()
while stack:
node = stack.pop()
if node == end:
return True
for neighbor in get_neighbors(maze, node):
if neighbor not in visited:
visited.add(neighbor)
stack.append(neighbor)
return False
def get_neighbors(maze, node):
# 根据实际情况获取邻居节点,比如二维数组
row, col = node
neighbors = [(row + dx, col + dy) for dx, dy in [(0, 1), (1, 0), (0, -1), (-1, 0)] if 0 <= row + dx < maze.shape[0] and 0 <= col + dy < maze.shape[1]]
return neighbors
```
2. **广度优先搜索 (BFS)**
```python
from collections import deque
def bfs(maze, start, end):
queue = deque([start])
visited = set()
while queue:
node = queue.popleft()
if node == end:
return True
visited.add(node)
for neighbor in get_neighbors(maze, node):
if neighbor not in visited:
queue.append(neighbor)
return False
```
3. **A*搜索算法(带启发式函数)**
```python
def a_star_search(maze, start, end, heuristic_func):
open_set = [(0, start)]
closed_set = set()
came_from = {}
g_score = {start: 0}
f_score = {start: heuristic_func(start, end)}
while open_set:
current = min(open_set, key=lambda x: f_score[x[1]])
open_set.remove(current)
closed_set.add(current[1])
if current[1] == end:
path = []
while current[1] != start:
path.append(current[1])
current = came_from[current[1]]
path.append(start)
path.reverse()
return path
for neighbor in get_neighbors(maze, current[1]):
tentative_g_score = g_score[current[1]] + 1
if neighbor not in closed_set or tentative_g_score < g_score.get(neighbor, float('inf')):
came_from[neighbor] = current[1]
g_score[neighbor] = tentative_g_score
f_score[neighbor] = g_score[neighbor] + heuristic_func(neighbor, end)
if neighbor not in open_set:
open_set.append((f_score[neighbor], neighbor))
```
以上代码都是基于某种数据结构(如列表、栈或队列)实现的。每个算法都有其特点,选择哪种取决于实际情况,比如是否需要保证最短路径,以及对内存消耗的要求。
阅读全文