a*寻路算法伪代码及实现

伪代码

设置一个待检测列表openList和一个不需检测列表closeList

把起始点startPoint推入openList;

然后检测openList

如果不为空就找出其中F值最小的一个 

将此节点做为当前节点(curNode),并且加入closeList中不再检测;

然后看看这个当前节点是不是我们要找的?

如果不是:

    遍历curNode周围的节点(矩阵网格的话,周围是8格,左,上,右,下,左上,右上,右下,左下)?

    如果是不可通过的、或者是在closeList中的、或者超过边界的都continue掉

    保存parent、F值到curNode上以便后续通过parent溯源,再保存在openList中

如果是:

    说明找到了(如果找到了就通过这个节点上保存的父节点层层查询,最终找到起始点,完成整条路径)

如果为空列表:

说明检测完了,但是没有找到目的地。

补充说明:

F值的计算公式:G(当前点和父节点的距离)+H(当前点和目的点的距离)))

G的值,如果是对角线的块按1.4倍长度来算

为了方便理解,我使用曼哈顿距离作为H的计算方式(横纵距离相加)

demo我放在gitee上,有兴趣的可以看一下,其实伪代码足以 

https://gitee.com/tang_c/my-shader-demo

  • 0
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
A*寻路算法是一种启发式搜索算法,用于在图形(如地图)中找到从起点到终点的最短路径。以下是一个基本的A*寻路算法实现,其中使用了一个优先队列来存储待扩展的节点。 ``` class Node: def __init__(self, x, y): self.x = x self.y = y self.g = 0 self.h = 0 self.f = 0 self.parent = None def __eq__(self, other): return self.x == other.x and self.y == other.y def __lt__(self, other): return self.f < other.f def astar(maze, start, end): # 初始化起点和终点节点 start_node = Node(start[0], start[1]) end_node = Node(end[0], end[1]) # 创建开放列表和关闭列表 open_list = [] closed_list = [] # 将起点加入开放列表 open_list.append(start_node) # 开始寻路循环 while len(open_list) > 0: # 从开放列表中找到f值最小的节点 current_node = min(open_list) open_list.remove(current_node) closed_list.append(current_node) # 判断是否到达终点节点 if current_node == end_node: path = [] while current_node is not None: path.append((current_node.x, current_node.y)) current_node = current_node.parent return path[::-1] # 获取当前节点相邻的节点 children = [] for new_pos in [(0, -1), (0, 1), (-1, 0), (1, 0)]: node_pos = (current_node.x + new_pos[0], current_node.y + new_pos[1]) # 确保节点在迷宫范围内 if node_pos[0] > (len(maze) - 1) or node_pos[0] < 0 or node_pos[1] > (len(maze[0]) - 1) or node_pos[1] < 0: continue # 确保节点不是障碍物 if maze[node_pos[0]][node_pos[1]] != 0: continue # 创建新节点并计算f值 new_node = Node(node_pos[0], node_pos[1]) new_node.parent = current_node new_node.g = current_node.g + 1 new_node.h = ((new_node.x - end_node.x) ** 2) + ((new_node.y - end_node.y) ** 2) new_node.f = new_node.g + new_node.h children.append(new_node) # 将子节点加入开放列表 for child in children: if child in closed_list: continue for open_node in open_list: if child == open_node and child.g > open_node.g: continue open_list.append(child) # 未找到路径 return None ``` 在上述实现中,Node类表示一个节点,其中包含节点的坐标、g值、h值和f值,以及指向父节点的指针。astar函数接受一个迷宫(表示障碍物和可行路径)以及起点和终点的坐标,并返回从起点到终点的最短路径。该函数使用一个优先队列来存储待扩展的节点,并在每次迭代中找到f值最小的节点进行扩展。在扩展节点时,该函数会计算每个相邻节点的f值,并将它们添加到开放列表中。如果找到终点节点,则该函数会回溯父节点以计算最短路径。如果未找到路径,则该函数返回None。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值