python实现路径规划算法实战

import heapq

class Node:
    def __init__(self, position, parent=None):
        self.position = position
        self.parent = parent
        self.g = 0  # 起点到当前节点的实际代价
        self.h = 0  # 当前节点到目标节点的预估代价
        self.f = 0  # f = g + h

    def __eq__(self, other):
        return self.position == other.position

def astar_search(start, end, grid):
    open_list = []  # 待探索的节点
    closed_list = set()  # 已探索的节点

    start_node = Node(start)
    end_node = Node(end)

    heapq.heappush(open_list, (0, start_node))

    while open_list:
        current_node = heapq.heappop(open_list)[1]
        closed_list.add(current_node)

        if current_node == end_node:
            path = []
            while current_node:
                path.append(current_node.position)
                current_node = current_node.parent
            return path[::-1]  # 返回反转后的路径

        children = []
        for new_position in [(0, -1), (0, 1), (-1, 0), (1, 0)]:  # 遍历当前节点的相邻节点
            node_position = (current_node.position[0] + new_position[0], current_node.position[1] + new_position[1])

            # 确保节点在地图内
            if node_position[0] > (len(grid) - 1) or node_position[0] < 0 or \
               node_position[1] > (len(grid[len(grid)-1]) -1) or node_position[1] < 0:
                continue

            # 确保节点不是障碍物
            if grid[node_position[0]][node_position[1]] == 1:
                continue

            new_node = Node(node_position, current_node)
            children.append(new_node)

        for child in children:
            if child in closed_list:
                continue

            # 计算g、h、f值
            child.g = current_node.g + 1
            child.h = ((child.position[0] - end_node.position[0]) ** 2) + \
                      ((child.position[1] - end_node.position[1]) ** 2)
            child.f = child.g + child.h

            # 如果该节点已经在open_list中,且新的g值更小,则更新该节点的信息
            for open_node in open_list:
                if child == open_node[1] and child.g > open_node[1].g:
                    continue

            heapq.heappush(open_list, (child.f, child))

    return None

# 示例地图
grid = [
    [0, 0, 0, 0, 0],
    [0, 1, 1, 1, 0],
    [0, 0, 0, 0, 0],
    [0, 1, 1, 1, 0],
    [0, 0, 0, 0, 0]
]

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

path = astar_search(start, end, grid)
if path:
    print("路径:", path)
else:
    print("未找到路径")

  • 6
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

程序员奇奇

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

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

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

打赏作者

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

抵扣说明:

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

余额充值