用python完成A*算法
时间: 2023-12-04 16:50:44 浏览: 63
A*算法python实现
5星 · 资源好评率100%
好的,以下是Python实现A*算法的示例代码:
```python
# 定义节点类
class Node:
def __init__(self, parent=None, position=None):
self.parent = parent
self.position = position
self.g = 0 # 从起点到当前节点的实际代价
self.h = 0 # 从当前节点到目标节点的估计代价
self.f = 0 # f = g + h
def __eq__(self, other):
return self.position == other.position
# 定义A*算法函数
def astar(maze, start, end):
# 初始化起点和终点
start_node = Node(None, start)
start_node.g = start_node.h = start_node.f = 0
end_node = Node(None, end)
end_node.g = end_node.h = end_node.f = 0
# 初始化开启列表和关闭列表
open_list = []
closed_list = []
# 将起点加入开启列表
open_list.append(start_node)
# 循环直到找到终点或者开启列表为空
while len(open_list) > 0:
# 获取f值最小的节点
current_node = open_list[0]
current_index = 0
for index, item in enumerate(open_list):
if item.f < current_node.f:
current_node = item
current_index = index
# 将当前节点从开启列表中移除,并加入关闭列表
open_list.pop(current_index)
closed_list.append(current_node)
# 判断是否找到终点
if current_node == end_node:
path = []
current = current_node
while current is not None:
path.append(current.position)
current = current.parent
return path[::-1] # 返回路径,倒序
# 获取当前节点的所有邻居
neighbors = []
for new_position in [(0, -1), (0, 1), (-1, 0), (1, 0), (-1, -1), (-1, 1), (1, -1), (1, 1)]:
node_position = (current_node.position[0] + new_position[0], current_node.position[1] + new_position[1])
# 确保节点在迷宫内
if node_position[0] > (len(maze) - 1) or node_position[0] < 0 or node_position[1] > (len(maze[len(maze)-1]) - 1) or node_position[1] < 0:
continue
# 确保节点不是墙
if maze[node_position[0]][node_position[1]] != 0:
continue
# 创建新节点
new_node = Node(current_node, node_position)
# 添加邻居
neighbors.append(new_node)
# 遍历所有邻居
for neighbor in neighbors:
# 如果邻居已经在关闭列表中,跳过
if neighbor in closed_list:
continue
# 计算邻居的f、g和h值
neighbor.g = current_node.g + 1
neighbor.h = ((neighbor.position[0] - end_node.position[0]) ** 2) + ((neighbor.position[1] - end_node.position[1]) ** 2)
neighbor.f = neighbor.g + neighbor.h
# 如果邻居已经在开启列表中,并且新的g值更大,跳过
for open_node in open_list:
if neighbor == open_node and neighbor.g > open_node.g:
continue
# 将邻居加入开启列表
open_list.append(neighbor)
```
其中maze表示迷宫,0表示可走,其他数字表示墙;start和end分别表示起点和终点的坐标。调用该函数即可得到从起点到终点的最短路径。
阅读全文