Python A*算法实现及案例讲解

A*算法是一种常用的路径规划算法,它结合了Dijkstra算法和贪心算法的优点,能够高效地找到起点到终点的最短路径。

本文将介绍如何使用Python实现A*算法,并通过一个案例演示其应用。

1. 代码实现

import heapq

# 定义节点类
class Node:
    def __init__(self, position, parent=None):
        self.position = position
        self.parent = parent
        self.g = 0  # 到起始点的实际代价
        self.h = 0  # 到目标点的估计代价
        self.f = 0  # 总代价
    
    def __lt__(self, other):
        return self.f < other.f

# 定义 A* 算法函数
def astar_algorithm(start, end, grid):
    open_list = []      # 存放待探索的节点
    closed_list = set() # 存放已探索的节点

    start_node = Node(start)
    end_node = Node(end)

    heapq.heappush(open_list, start_node)

    while open_list:
        current_node = heapq.heappop(open_list)

        if current_node.position == end_node.position:
            path = []
            while current_node:
                path.append(current_node.position)
                current_node = current_node.parent
            path.reverse()
            return path
        
        closed_list.add(current_node.position)

        neighbors = get_neighbors(current_node.position, grid)

        for neighbor in neighbors:
            if neighbor in closed_list:
                continue

            neighbor_node = Node(neighbor, current_node)
            neighbor_node.g = current_node.g + 1
            neighbor_node.h = heuristic(neighbor, end_node.position)
            neighbor_node.f = neighbor_node.g + neighbor_node.h

            if neighbor not in [node.position for node in open_list]:
                heapq.heappush(open_list, neighbor_node)
            else:
                for node in open_list:
                    if node.position == neighbor_node.position and node.f > neighbor_node.f:
                        node = neighbor_node
                        break

    return None

# 定义获取邻居节点的函数
def get_neighbors(position, grid):
    rows = len(grid)
    cols = len(grid[0])
    x, y = position

    neighbors = []

    if x > 0 and not grid[x-1][y]: # 上
        neighbors.append((x-1, y))

    if x < rows-1 and not grid[x+1][y]: # 下
        neighbors.append((x+1, y))

    if y > 0 and not grid[x][y-1]: # 左
        neighbors.append((x, y-1))

    if y < cols-1 and not grid[x][y+1]: # 右
        neighbors.append((x, y+1))

    return neighbors

# 定义启发函数(这里使用曼哈顿距离)
def heuristic(position, target):
    return abs(position[0] - target[0]) + abs(position[1] - target[1])

# 测试
grid = [
    [0, 0, 0, 0, 0],
    [0, 1, 1, 0, 0],
    [0, 0, 0, 0, 0],
    [0, 0, 1, 1, 0],
    [0, 0, 0, 0, 0]
]

start = (0, 0)
end = (4, 4)

path = astar_algorithm(start, end, grid)

if path:
    print('找到最短路径:')
    for position in path:
        print(position)
else:
    print('无法找到路径')

2. 代码解释

  • 节点类 Node: 用于表示地图上的节点,包含位置、父节点、实际代价 g、估计代价 h 和总代价 f 等信息。
  • astar_algorithm 函数: 实现 A* 算法的核心函数,接受起点、终点和地图信息作为输入,返回最短路径。
    • 使用 open_listclosed_list 分别存储待探索和已探索的节点。
    • 使用优先队列 heapq 实现 open_list,以便快速找到 f 值最小的节点。
    • 使用 get_neighbors 函数获取当前节点的邻居节点。
    • 使用 heuristic 函数计算估计代价 h
    • 当找到终点时,通过回溯父节点构建最短路径。
  • get_neighbors 函数: 根据当前节点的位置和地图信息,获取可到达的邻居节点。
  • heuristic 函数: 计算当前节点到终点的估计代价,这里使用曼哈顿距离作为启发函数。

3. 案例演示

在上面的代码中,我们定义了一个 5x5 的地图 grid,其中 1 表示障碍物,0 表示可通行区域。起点为 (0, 0),终点为 (4, 4)。运行代码后,将输出找到的最短路径。

4. 总结

本文介绍了使用Python实现A算法的方法,并通过案例演示了其应用。A算法是一种高效的路径规划算法,可以应用于各种场景,例如游戏开发、机器人导航等。

Python A*算法实现及案例讲解

原文地址: https://www.cveoy.top/t/topic/C94 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录