← 全部技术笔记

机器人 · 路径规划

在障碍网格上逐步看懂 A* 路径规划

加入“离目标还有多远”的估计后,搜索范围能缩小多少?编辑障碍、切换A*与Dijkstra,同时比较路径长度和扩展节点数。

一手资料核验日期:2026年8月31日

01

让搜索前沿动起来

点击单元格编辑障碍。Step每次扩展一个节点,Run会持续运行到找到目标或确认无路可走。

已扩展
0
候选
1
路径长度
—

绿色是起点,红色是目标,深蓝是已确定节点,黄色是候选节点,白线是最终路径。

02

A*多加的,是对剩余距离的估计

Dijkstra按照已经付出的实际代价g向外搜索。A*再加入到目标的估计代价h,并使用f = g + h选择下一个位置。

本图解只允许上下左右移动,因此使用曼哈顿距离作为h。切换到Dijkstra时h为0。最终路径可能不变,但被检查的区域会明显不同。

03

启发式函数提供方向,不保证凭空出现捷径

当h不高估真实剩余代价时,A*可以在保持最短路径性质的同时缩小搜索范围。地图、运动模型或代价定义一变,合适的h也会改变。

真实机器人还要处理外形、转弯半径、膨胀代价、动态障碍和重新规划。Nav2的Smac Planner包含2D A*、Hybrid-A*与State Lattice,本页的四邻域网格只是教学模型。

04

最小Python实现

只使用标准库heapq,返回从起点到目标的单元格序列。

Python 3a_star_grid.py
from heapq import heappop, heappush

def astar(grid, start, goal):
    """4-neighbour A* for a grid where 1 means blocked."""
    height, width = len(grid), len(grid[0])
    frontier = [(0, start)]
    came_from = {start: None}
    cost = {start: 0}

    def heuristic(cell):
        return abs(cell[0] - goal[0]) + abs(cell[1] - goal[1])

    while frontier:
        _, current = heappop(frontier)
        if current == goal:
            break

        row, col = current
        for next_cell in ((row-1, col), (row+1, col),
                          (row, col-1), (row, col+1)):
            r, c = next_cell
            if not (0 <= r < height and 0 <= c < width):
                continue
            if grid[r][c] == 1:
                continue

            new_cost = cost[current] + 1
            if next_cell not in cost or new_cost < cost[next_cell]:
                cost[next_cell] = new_cost
                priority = new_cost + heuristic(next_cell)
                heappush(frontier, (priority, next_cell))
                came_from[next_cell] = current

    if goal not in came_from:
        return []

    path, current = [], goal
    while current is not None:
        path.append(current)
        current = came_from[current]
    return path[::-1]

05

这个示例刻意没有包含

06

核验的一手资料

  1. Hart, Nilsson, Raphael (1968), A Formal Basis for the Heuristic Determination of Minimum Cost Paths

    用于确认A*评价函数和最优性基础的原始论文。

  2. ROS 2 Navigation2 — Smac Planner

    核对当前2D A*、Hybrid-A*与State Lattice规划器的范围。

  3. Navigation2 Planner Server

    核对规划器插件在ROS 2导航栈中的位置。