A*(A星)路径搜索算法属于启发式搜索算法范式。
下面是一个简单的Python代码示例,展示如何使用A*算法搜索最短路径:
class Node:
def __init__(self, x, y, cost=0, heuristic=0, parent=None):
self.x = x
self.y = y
self.cost = cost
self.heuristic = heuristic
self.parent = parent
def total_cost(self):
return self.cost + self.heuristic
def heuristic(node, goal):
return abs(node.x - goal.x) + abs(node.y - goal.y)
def astar_search(start, goal, grid):
open_list = []
closed_list = []
open_list.append(start)
while open_list:
current_node = min(open_list, key=lambda node: node.total_cost())
if current_node == goal:
path = []
while current_node:
path.append((current_node.x, current_node.y))
current_node = current_node.parent
return path[::-1]
open_list.remove(current_node)
closed_list.append(current_node)
neighbors = [(current_node.x - 1, current_node.y),
(current_node.x + 1, current_node.y),
(current_node.x, current_node.y - 1),
(current_node.x, current_node.y + 1)]
for neighbor_x, neighbor_y in neighbors:
if (neighbor_x < 0 or neighbor_x >= len(grid) or
neighbor_y < 0 or neighbor_y >= len(grid[0]) or
grid[neighbor_x][neighbor_y] == 1):
continue
neighbor = Node(neighbor_x, neighbor_y)
neighbor.cost = current_node.cost + 1
neighbor.heuristic = heuristic(neighbor, goal)
neighbor.parent = current_node
if neighbor in closed_list:
continue
if neighbor in open_list:
if neighbor.cost < current_node.cost:
neighbor.parent = current_node
else:
open_list.append(neighbor)
return None
# 示例使用
grid = [[0, 0, 1, 0, 0],
[0, 0, 1, 0, 0],
[0, 0, 0, 0, 0],
[0, 0, 1, 0, 0],
[0, 0, 0, 0, 0]]
start = Node(0, 0)
goal = Node(4, 4)
path = astar_search(start, goal, grid)
print(path)
该示例中,Node
类表示搜索中的节点,heuristic
函数计算节点和目标节点之间的启发式估计值,astar_search
函数执行A*搜索算法。在示例中,我们使用一个5x5的网格来表示地图,其中0表示可以通过的路径,1表示障碍物。起始节点为(0, 0),目标节点为(4, 4)。最后,通过调用astar_search
函数,我们得到了最短路径的坐标序列。