AI Wiki中文/EN

A* search

A* 搜索

Combine cost so far with estimated remaining cost to find shortest paths under explicit assumptions.

On this pageIntuitionMathematics & methodImplementationLimitationsExercisesResearch connections

Intuition: how far have we traveled, and what remains?

Choosing the position that looks closest to a destination ignores the cost of reaching it. Considering only cost already incurred can explore many unpromising directions. A* combines the two: retain the best known cost so far, g(n)g(n), estimate remaining cost with h(n)h(n), and prioritize states by f(n)=g(n)+h(n)f(n)=g(n)+h(n).

A heuristic is not an arbitrary decorative guess. It directs computational effort, and its properties determine which optimality claims hold. The classic formal analysis is due to Hart, Nilsson, and Raphael; the AIMA project provides implementations and comparisons with other search methods. Original paper, AIMA Python

Method and conditions for optimality

If h∗(n)h^*(n) is the true minimum remaining cost, an admissible heuristic satisfies 0≤h(n)≤h∗(n)0\leq h(n)\leq h^*(n): it never overestimates. A consistent heuristic additionally satisfies h(n)≤c(n,n′)+h(n′)h(n)\leq c(n,n')+h(n') on every edge. Consistency makes ff nondecreasing along a path and supports closing expanded states under the appropriate graph-search conditions.

An admissible but inconsistent heuristic can require reopening a state after discovering a cheaper route. The implementation here allows a better gg value to reenter the queue rather than permanently forbidding revisits. Success is checked when the goal is removed from the queue, not merely when it is first discovered.

For a finite graph with nonnegative costs, an admissible heuristic, and h(goal)=0h(goal)=0, this reopening approach supports a shortest-path guarantee. Infinite state spaces require additional completeness conditions. Setting h=0h=0 gives uniform-cost search. Multiplying a heuristic by a weight greater than one can accelerate search but generally sacrifices the optimality guarantee.

Manhattan distance is admissible and consistent on a four-neighbor grid with unit-cost moves. Diagonal movement or different costs require reassessment. Complexity depends on the graph, heuristic, and repeated expansions. A* can still search a very large state space in the worst case; intelligent prioritization does not imply universal efficiency.

A runnable graph search

import heapq
import math
from itertools import count

def astar(graph, start, goal, heuristic, expanded=None):
    nodes = set(graph) | {start,goal}
    for edges in graph.values():
        for nxt,weight in edges:
            nodes.add(nxt)
            if not math.isfinite(weight) or weight < 0:
                raise ValueError("finite nonnegative edges required")
    h = {node:heuristic(node) for node in nodes}
    if any(not math.isfinite(v) or v < 0 for v in h.values()) or h[goal] != 0:
        raise ValueError("finite nonnegative heuristic with zero goal value required")
    serial = count()
    queue = [(h[start],0,next(serial),start)]
    best, parent = {start:0}, {}
    while queue:
        _,cost,_,node = heapq.heappop(queue)
        if cost != best[node]:
            continue
        if node == goal:
            path = [node]
            while node in parent:
                node = parent[node]
                path.append(node)
            return cost,path[::-1]
        if expanded is not None:
            expanded.append(node)
        for nxt,weight in graph.get(node,[]):
            candidate = cost+weight
            priority = candidate+h[nxt]
            if not math.isfinite(candidate) or not math.isfinite(priority):
                raise ArithmeticError("nonfinite path cost or priority")
            if candidate < best.get(nxt,math.inf):
                best[nxt],parent[nxt] = candidate,node
                heapq.heappush(queue,(priority,candidate,next(serial),nxt))
    return None

graph = {'S':[('A',2),('B',1)],'B':[('A',0.5)],'A':[('G',1)]}
assert astar(graph,'S','G',lambda _:0) == (2.5,['S','B','A','G'])
reopen = {'S':[('A',3),('B',1)],'B':[('A',1)],'A':[('G',3)]}
h = {'S':0,'A':0,'B':4,'G':0}
trace = []
assert astar(reopen,'S','G',h.get,trace) == (5,['S','B','A','G'])
assert trace == ['S','A','B','A']
assert astar({'S':[('S',0)]},'S','G',lambda _:0) is None
assert astar({},'S','S',lambda _:0) == (0,['S'])
try:
    astar({'S':[('G',1)],'unused':[('G',-1)]},'S','G',lambda _:0)
except ValueError:
    pass
else:
    raise AssertionError("negative edge hidden by early goal return")

Keeping old queue entries and skipping them when popped avoids implementing decrease-key. A serial number breaks priority ties without requiring state objects to be orderable.

Why is removal of the goal safe? Before a suboptimal goal of cost C>C∗C>C^* could be removed, a frontier entry on an optimal route would have g+h≤C∗g+h\le C^*. Allowing improved routes to reenter preserves this possibility when an earlier expansion used a worse cost. The priority queue would choose that entry first, contradicting removal of the more expensive goal. The argument assumes admissibility and the stated finite nonnegative-cost setting; input validation alone cannot prove a user-supplied heuristic admissible. CS188, A* and heuristic properties

In the second code example, A is first expanded at cost 3. B’s admissible estimate is 4, so B is expanded later and improves A’s cost to 2. A must be expanded again, giving total cost 5 instead of 6. The recorded expansion order verifies this reopening directly.

With a consistent heuristic, finite adjacency lists, and a lazy binary heap, search bookkeeping takes O(V+Elog⁡(E+1))O(V+E\log(E+1)) time and O(V+E)O(V+E) extra space, including potentially stale entries. Heuristic evaluation is additional work, cached once per vertex here. Inconsistent admissible heuristics can cause repeated expansions, so the same bound cannot be promised generally. The fixed AIMA implementation uses a closed set; this example intentionally supports a different reopening policy.

Limitations and misconceptions

Optimality applies to the state representation and cost function you supplied. Missing roads or costs that ignore risk can produce a formally optimal but practically unsuitable route. A state must retain information that affects future transitions, such as remaining fuel. Merging two states solely because they share a location can invalidate the model.

The cost of calculating the heuristic also matters. A highly accurate but expensive estimate may erase the benefit of fewer expansions. Report path quality, expanded states, runtime, and memory rather than a single favorable statistic.

Experiments and exercises

  1. How many moves cross an empty 6×6 four-neighbor grid from top-left to bottom-right? Answer: 10.
  2. What happens when h=0h=0? Answer: uniform-cost search; with equal edge costs, its distance layers align with BFS.
  3. Does multiplying the heuristic by three preserve an unconditional optimality promise? Answer: no; it generally breaks admissibility.
  4. Why is the second example’s heuristic inconsistent? Answer: on B→A, h(B)=4>1+h(A)=1h(B)=4>1+h(A)=1. It is still admissible because B’s true remaining cost is 4. Reopening A gives the correct route cost 5.

Research connections

IDA* addresses memory limits. Pattern databases and planning heuristics offer ways to construct estimates, while bidirectional search explores from both endpoints. When a learned model estimates remaining cost, evaluate predictive accuracy and admissibility separately. Low average prediction error does not mean the model never overestimates.

Make a prediction, then check

What generally happens to optimality when an admissible heuristic is multiplied by 3?

Choose one answer

Learning objectives

  • Explain admissibility, consistency, and reopening states.
  • Implement priority-queue search and check path costs.

Prerequisites & connections

Explore related knowledge →

References

  1. A Formal Basis for the Heuristic Determination of Minimum Cost Paths
    Peter E. Hart; Nils J. Nilsson; Bertram Raphael · 1968
  2. AIMA Python
    AIMA contributors
  3. CS188 Textbook — Informed Search
    UC Berkeley CS188 course contributors
  4. AIMA Python — search algorithms (commit f104e03, 2026-06-30)
    AIMA Python contributors · 2026

Version2 · Editorial status: Recorded technical checks completed

View technical check record (AI)

Codex · 2026-09-05 · Codex technical check: cited-source comparison, re-derivation and recalculation, bilingual argument comparison, and executed Python assertions; no independent human peer review.

  • Executed S→A→B→A re-expansion, obtaining S→B→A→G at cost 5; independently enumerated all simple paths in 100 random six-vertex graphs.
  • Checked unreachable goals, zero-cost cycles, and hidden negative edges; distinguished the finite nonnegative graph setting from the original broader termination proof.
  • Compared the main claims, assumptions, examples, exercises, and citations across languages; structural checks additionally compare display equations, code, and source IDs. This is an AI technical check, not independent human peer review.

Source locations checked:

Related topics

No matches. Try a synonym or acronym.

0 results shown

Wrap the whole query in double quotes for a phrase match.