AStar寻路算法的Python实现
2024.01.17 22:05浏览量:14简介:本文将介绍AStar寻路算法的基本原理,并给出Python实现代码。通过阅读本文,读者将了解如何使用AStar算法在地图上找到从起点到终点的最短路径。
AStar寻路算法是一种启发式搜索算法,用于在图形中找到从起点到终点的最短路径。它使用启发式函数来评估每个节点的优先级,以便优先搜索最有可能导致目标节点的节点。
AStar算法的核心思想是使用两个堆栈:open list和close list。open list存储当前正在考虑的节点,close list存储已经考虑过的节点。算法从起点节点开始,将其添加到open list中。然后,从open list中选择优先级最高的节点,并检查其相邻节点。如果相邻节点不在close list中,则将其添加到open list中。然后,将该节点添加到close list中,并更新其父节点。重复此过程,直到找到目标节点或open list为空。
下面是AStar寻路算法的Python实现代码:
```python
import heapq
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 heuristic(node1, node2):
曼哈顿距离作为启发式函数
return abs(node1.x - node2.x) + abs(node1.y - node2.y)
def astar(start, goal, grid):
初始化节点列表和open list
open_list = []
closed_list = set()
start_node = Node(start[0], start[1])
start_node.g = start_node.h = start_node.f = 0
heapq.heappush(open_list, start_node)
while open_list:
current_node = heapq.heappop(open_list)
if current_node in closed_list:
continue
closed_list.add(current_node)
if current_node == goal:
return current_node.path()
for next_node in get_neighbors(current_node, grid):
if next_node in closed_list and next_node.g > current_node.g:
continue
next_node.g = current_node.g + 1
next_node.h = heuristic(next_node, goal)
next_node.f = next_node.g + next_node.h
if next_node not in open_list or next_node.f > open_list[0].f:
next_node.parent = current_node
heapq.heappush(open_list, next_node)
return None
def get_neighbors(node, grid):
neighbors = []
for x in [-1, 0, 1]:
for y in [-1, 0, 1]:
if x == 0 and y == 0: # 不包括当前节点本身
continue
next_node = Node(node.x + x, node.y + y)
if (next_node.x < 0 or next_node.y < 0 or next_node.x >= len(grid) or next_node.y >= len(grid[0])): # 越界情况,不可通行
continue
if grid[next_node.x][next_node.y] == 1: # 可通行情况,添加到邻居列表中
neighbors.append(next_node)
return neighbors

发表评论
登录后可评论,请前往 登录 或 注册