A星算法是一种启发式搜索算法,用于寻找从起点到终点的最短路径。下面是一个简单的Python实现示例,使用了一个自定义的`Map2D`类来表示地图,以及一个`PriorityQueue`类来实现优先队列。
import heapqclass PriorityQueue:def __init__(self):self.elements = []def push(self, item, priority):heapq.heappush(self.elements, (priority, item))def pop(self):return heapq.heappop(self.elements)class Map2D:def __init__(self, width=20, height=20):self.width = widthself.height = heightself.map = [[0 for _ in range(width)] for _ in range(height)]def set_cell(self, x, y, value):if 0 <= x < self.width and 0 <= y < self.height:self.map[y][x] = valuedef get_cell(self, x, y):if 0 <= x < self.width and 0 <= y < self.height:return self.map[y][x]return Nonedef heuristic(a, b):return abs(a - b) + abs(a - b) Manhattan distancedef a_star_search(graph, start, goal):open_set = PriorityQueue()closed_set = set()g = {start: 0}f = {start: heuristic(start, goal)}parents = {start: None}open_set.push(start, f[start])while open_set.elements:current = open_set.pop()if current == goal:path = []while current is not None:path.append(current)current = parents[current]return path[::-1]closed_set.add(current)for dx, dy in [(0, 1), (1, 0), (0, -1), (-1, 0)]: Right, Down, Left, Upneighbor = (current + dx, current + dy)tentative_g = g[current] + 1if 0 <= neighbor < len(graph) and 0 <= neighbor < len(graph) and graph[neighbor][neighbor] == 0:if neighbor in closed_set and tentative_g >= g.get(neighbor, 0):continueif neighbor not in open_set or tentative_g < g.get(neighbor, 0) or heuristic(current, neighbor) < f.get(neighbor, 0):parents[neighbor] = currentg[neighbor] = tentative_gf[neighbor] = tentative_g + heuristic(neighbor, goal)open_set.push(neighbor, f[neighbor])return None No path foundExample usage:Initialize the mapmap_instance = Map2D()map_instance.set_cell(0, 0, 0) Walkable cellmap_instance.set_cell(1, 1, 0) Walkable cellmap_instance.set_cell(2, 2, 1) Wall... set other cells ...Define start and goal pointsstart = (0, 0)goal = (2, 2)Run A* searchpath = a_star_search(map_instance, start, goal)if path:print("Path found:")for point in path:print(point)else:print("No path found.")
这个代码示例定义了一个`Map2D`类来表示地图,其中`0`表示可通行的格子,`1`表示墙壁。`a_star_search`函数实现了A星算法,使用优先队列来管理开放列表,并使用曼哈顿距离作为启发函数。
请注意,这个示例是一个简化的版本,实际应用中可能需要根据具体问题调整地图表示、启发函数和搜索逻辑。此外,示例中没有包含地图的显示功能,你可以根据需要添加绘图代码来可视化搜索过程和结果

