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

迷宫求解问题通常可以通过图搜索算法来解决,常用的方法包括广度优先搜索(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字典追溯找到的路径。

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

相关推荐
聚客AI1 天前
🙋‍♀️Transformer训练与推理全流程:从输入处理到输出生成
人工智能·算法·llm
大怪v1 天前
前端:人工智能?我也会啊!来个花活,😎😎😎“自动驾驶”整起!
前端·javascript·算法
惯导马工1 天前
【论文导读】ORB-SLAM3:An Accurate Open-Source Library for Visual, Visual-Inertial and
深度学习·算法
骑自行车的码农1 天前
【React用到的一些算法】游标和栈
算法·react.js
博笙困了1 天前
AcWing学习——双指针算法
c++·算法
moonlifesudo1 天前
322:零钱兑换(三种方法)
算法
NAGNIP2 天前
大模型框架性能优化策略:延迟、吞吐量与成本权衡
算法
美团技术团队2 天前
LongCat-Flash:如何使用 SGLang 部署美团 Agentic 模型
人工智能·算法
Fanxt_Ja2 天前
【LeetCode】算法详解#15 ---环形链表II
数据结构·算法·leetcode·链表
侃侃_天下2 天前
最终的信号类
开发语言·c++·算法