迷宫求解:探索最优路径的算法与应用

迷宫求解问题通常可以通过图搜索算法来解决,常用的方法包括广度优先搜索(BFS)、深度优先搜索(DFS)和A*算法。以下是一个使用BFS解决迷宫问题的Python示例:

Python 迷宫求解代码示例

python 复制代码
from collections import deque

def is_valid_move(maze, visited, position):
    x, y = position
    return (0 <= x < len(maze)) and (0 <= y < len(maze[0])) and (maze[x][y] == 0 and not visited[x][y])

def bfs(maze, start, end):
    queue = deque([start])
    visited = [[False] * len(maze[0]) for _ in range(len(maze))]
    visited[start[0]][start[1]] = True
    parent = {start: None}

    while queue:
        current = queue.popleft()
        if current == end:
            break

        x, y = current
        for dx, dy in [(-1, 0), (1, 0), (0, -1), (0, 1)]:  # 上、下、左、右
            neighbor = (x + dx, y + dy)
            if is_valid_move(maze, visited, neighbor):
                visited[neighbor[0]][neighbor[1]] = True
                queue.append(neighbor)
                parent[neighbor] = current

    # 追溯路径
    path = []
    while current is not None:
        path.append(current)
        current = parent[current]
    path.reverse()  # 反转路径

    return path if path[0] == start else []

# 示例迷宫,0表示通路,1表示墙
maze = [
    [0, 1, 0, 0, 0],
    [0, 1, 0, 1, 0],
    [0, 0, 0, 1, 0],
    [0, 1, 0, 0, 0],
    [0, 0, 1, 1, 0]
]

start = (0, 0)  # 起点
end = (4, 4)    # 终点

path = bfs(maze, start, end)

if path:
    print("找到路径:", path)
else:
    print("无路径可达")

代码说明

  1. 迷宫表示:使用二维数组,0表示通路,1表示墙。
  2. is_valid_move:检查是否可以移动到指定位置。
  3. bfs:使用BFS算法从起点搜索到终点,维护一个队列和已访问的状态。
  4. 路径追溯 :通过parent字典追溯找到的路径。

你可以根据自己的需要修改迷宫的布局和起点、终点的位置。

相关推荐
烬羽17 小时前
字符串算法入门:从反转字符串到回文判断,面试不再慌
算法·面试
先吃饱再说1 天前
判断回文字符串,从一行代码到双指针优化
算法
黄敬峰1 天前
深入理解算法核心:从递归思想、数组扁平化到快速排序
算法
得物技术2 天前
从狂野代码到按目标生产:得物推荐 AI Harness 的工程化实践|AICon 演讲整理
人工智能·算法·架构
AI小老六2 天前
SkillOpt 架构拆解:把 Skill 文本当参数,用执行轨迹训练 Agent
后端·算法·ai编程
胡萝卜术2 天前
从“分数打架”到“排名投票”:为什么你的ChatBI必须用RRF?
算法·设计模式·面试
Asize2 天前
初识DFS 与 BFS:递归、队列与图遍历
算法
罗西的思考2 天前
机器人 / 强化学习】HIL-SERL:人类在环驱动的具身智能进化框架
人工智能·算法·机器学习
美团技术团队2 天前
LongCat 开源 VitaBench 2.0:长期动态智能体基准新标杆
人工智能·算法