# 开始搜索 whilelen(open_set) > 0: # 获取距离目标最近的节点 current = heapq.heappop(open_set)[1]
# 如果当前节点是目标节点 if current == goal: path = [] while current in came_from: path.append(current) current = came_from[current] path.append(start) path.reverse() return path
# 加入闭合集合 closed_set.add(current)
# 遍历相邻节点 for x, y in [(0, 1), (0, -1), (1, 0), (-1, 0)]: neighbor = current[0] + x, current[1] + y # 如果邻居节点已经处理过了或者有障碍物 if neighbor in closed_set or neighbor in obstacles: continue
# 计算估价函数值 tentative_g_score = heuristic(start, neighbor) if tentative_g_score notin open_set: heapq.heappush(open_set, (tentative_g_score, neighbor)) came_from[neighbor] = current