A* (A-Star) 是啟發式圖搜索算法,結合 Dijkstra 保證最短路徑與貪心策略加速收斂,廣泛用於遊戲寻路、機器人規劃、網絡路由。本文提供生產級 Java 實現,含八方向移動、代價模型、開閉集合優化、路徑回溯與可視化測試。
class Node {
int x, y; // 坐標
Node parent; // 父節點(回溯用)
int g; // 起點到當前實際代價
int h; // 當前到終點估算代價(曼哈頓/歐幾里得/切比雪夫)
int f; // f = g + h,優先級依據
}
COST_STRAIGHT = 10COST_DIAGONAL = 14(≈10×√2)// 核心搜索
private List<Node> search(Node start, Node end) {
List<Node> path = new ArrayList<>();
openList.add(start);
while (!openList.isEmpty()) {
Node cur = openList.get(0); // 已按 f 排序
if (cur.x == end.x && cur.y == end.y) {
buildPath(path, cur);
return path;
}
for (Direction dir : Direction.values()) {
Node next = cur.neighbor(dir);
if (!isValid(next) || inCloseList(next)) continue;
int newG = cur.g + dir.cost;
int idx = indexInOpenList(next);
if (idx >= 0) {
if (newG < openList.get(idx).g) updateNode(openList.get(idx), cur, newG);
} else {
openList.add(new Node(next.x, next.y, cur, newG, heuristic(next, end)));
}
}
closeList.add(openList.remove(0));
Collections.sort(openList, Comparator.comparingInt(n -> n.f));
}
return path; // 空 = 失敗
}
| 場景 | 啟發式 h(n) | 屬性 |
|---|---|---|
| 四方向網格 | 曼哈頓距離 |dx|+|dy| | 可接受、單調 |
| 八方向網格 | 切比雪夫距離 max(|dx|,|dy|) | 可接受、單調 |
| 任意角度移動 | 歐幾里得距離 sqrt(dx²+dy²) | 可接受、非單調 |