使用广度优先搜索算法找到最短路径,然后绘制路径图

本文介绍了如何使用广度优先搜索(BFS)算法在一个网格环境中找到从起点到终点的最短路径,并展示了如何将搜索过程中的路径可视化为三维图形。
摘要由CSDN通过智能技术生成

使用广度优先搜索算法找到最短路径,然后绘制路径图

from collections import deque
import matplotlib.pyplot as plt

# 定义网格环境的参数
GRID_SIZE = 5
GRID_WIDTH = 4
AGENT_SPEED = 2
START_STATE = (0, 0)
GOAL_STATE = (GRID_SIZE - 1, GRID_SIZE - 1)

# 定义动作集合:上、下、左、右
ACTIONS = ['UP', 'DOWN', 'LEFT', 'RIGHT']
NUM_ACTIONS = len(ACTIONS)

# 定义参数
EPSILON = 0.1  # 探索率

# 定义动作对应的坐标增量
ACTION_DELTA = {
    'UP': (-AGENT_SPEED, 0),
    'DOWN': (AGENT_SPEED, 0),
    'LEFT': (0, -AGENT_SPEED),
    'RIGHT': (0, AGENT_SPEED)
}

# 执行广度优先搜索(BFS)算法找到最短路径
def bfs():
    queue = deque([(START_STATE, [])])
    visited = set()
    
    while queue:
        current_state, path = queue.popleft()
        if current_state == GOAL_STATE:
            return path
        visited.add(current_state)
        for action in ACTIONS:
            next_state = take_action(current_state, action)
            if next_state not in visited and is_valid_state(next_state):
                queue.append((next_state, path + [action]))

# 检查状态是否有效(在网格范围内)
def is_valid_state(state):
    x, y = state
    return 0 <= x < GRID_SIZE and 0 <= y < GRID_SIZE

# 执行动作
def take_action(state, action):
    dx, dy = ACTION_DELTA[action]
    x, y = state
    next_state = (x + dx, y + dy)
    return next_state

# 绘制路径图
def plot_path(path):
    x_coords = [START_STATE[0]]  # 起点 x 坐标
    y_coords = [START_STATE[1]]  # 起点 y 坐标
    z_coords = [0]  # 时间轴

    for action in path:
        dx, dy = ACTION_DELTA[action]
        x_coords.append(x_coords[-1] + dx)
        y_coords.append(y_coords[-1] + dy)
        z_coords.append(len(z_coords))

    fig = plt.figure()
    ax = fig.add_subplot(111, projection='3d')
    ax.plot(x_coords, y_coords, z_coords)
    ax.set_xlabel('X')
    ax.set_ylabel('Y')
    ax.set_zlabel('Time Step')
    plt.title('Shortest Path of the Agent')
    plt.show()

# 执行广度优先搜索找到最短路径
shortest_path = bfs()

# 输出最短路径
print("Shortest Path:", shortest_path)

# 绘制最短路径的三维图形
plot_path(shortest_path)

寻优路线图!
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

喝凉白开都长肉的大胖子

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值