A*(A星)算法是一种启发式搜索算法,用于找到两点之间最短路径。它是行业标准的原因在于它的效率和准确性。相对于其他寻路算法,它对机器的处理速度和内存的占用比较友好。同时,它能够在寻找路径的同时考虑启发式估价函数(h函数)和实际代价(g函数),可以保证路径的最优性。
以下是A*算法的实现代码,用来求解一个迷宫地图的最短路径。
class AStar:
def __init__(self, graph):
self.graph = graph
def heuristic(self, start, end):
# 使用Manhattan距离作为估价函数
return abs(start[0] - end[0]) + abs(start[1] - end[1])
def astar_path(self, start, end):
frontier = PriorityQueue()
frontier.put(start, 0)
came_from = {}
came_from[start] = None
g_score = {node: float("inf") for row in self.graph for node in row}
g_score[start] = 0
f_score = {node: float("inf") for row in self.graph for node in row}
f_score[start] = self.heuristic(start, end)
while not frontier.empty():
current = frontier.get()
if current == end:
path = []
while current in came_from:
path.append(current)
current = came_from[current]
return path[::-1]
for neighbor in self.get_neighbors(current):
tentative_g_score = g_score[current] + 1
if tentative_g_score < g_score[neighbor]:
came_from[neighbor] = current
g_score[neighbor] = tentative_g_score
f_score[neighbor] = tentative_g_score + self.heuristic(neighbor, end)
if neighbor not in frontier.queue: