#1 India's Top IT Training Institute
×

About Uncodemy

Know more about who we are and what we stand for.

About Us

About Us

Discover our mission to equip individuals with essential IT skills and industry expertise.

Read More →
UnCodeMy Gallery

UnCodeMy Gallery

Explore highlights from our IT training sessions and success stories.

Read More →
Mentors

Mentors

Meet the industry experts who train and guide you through your course.

Read More →
Free Resources

Free Resources

Free tutorials, interview questions, tools and calculators to help you learn.

Explore →
×

Free Resources

Learn, practice and plan your career — bilkul free.

Tutorials

Tutorials

Step-by-step written tutorials to learn any technology at your own pace.

Read More →
Free Counselling

Free Counselling

Book a free video counselling session and pick the right course for you.

Read More →
Online Compiler

Online Compiler

Write, run and test your code online — no setup required.

Read More →
Home / Blog /

AO* Algorithm in AI

Heuristic Search for AND-OR Graphs

Published
7 min read
Scroll Down

What is the AO* algorithm?

AO* (read "A-O-star") is a best-first heuristic search algorithm for AND-OR graphs. It is used when a problem can be broken into smaller subproblems, an approach called problem reduction. The classic presentation is in Nilsson's Principles of Artificial Intelligence and in Rich and Knight's Artificial Intelligence, which this page follows.

In an ordinary search graph, every branch is an alternative: you need to solve only one. In an AND-OR graph there are two kinds of branch:

  • OR branch: the node can be solved by solving any one of its successors. "To get a car, either buy one or borrow one."
  • AND arc: the node is solved only if all successors joined by the arc are solved. "To buy a car, get the money AND go to the dealer." An AND arc is drawn as a curve joining the edges.

So the answer AO* returns is not a single path but a solution graph (often a tree): from the start node, one chosen arc at every node, down to nodes that are directly solvable (terminal or primitive problems).

Why A* cannot be used directly

The A* algorithm scores each path by f(n) = g(n) + h(n) and expands the best path. In an AND-OR graph that does not work, because the cost of an AND arc depends on several successors at once, and because a promising-looking node may turn out to be expensive only after its whole subtree is explored. AO* handles this by keeping the cost estimate at every node and revising those estimates upward through the graph each time it expands something. The best partial solution can therefore switch from one branch to another during the search.

AO* algorithm: steps

Notation: h(n) is the current estimate of the cost of solving n; FUTILITY is a large threshold above which the problem is treated as unsolvable.

  1. Let GRAPH contain only the start node INIT. Compute h(INIT).
  2. Repeat until INIT is labelled SOLVED, or h(INIT) exceeds FUTILITY:
    1. Follow the currently marked (best) arcs from INIT and pick one node on this best partial solution graph that has not been expanded yet. Call it NODE.
    2. Generate the successors of NODE. If it has none, set h(NODE) = FUTILITY: it cannot be solved. Otherwise add each successor to GRAPH (skipping any that is an ancestor of NODE, to avoid cycles). Label terminal successors SOLVED with h = 0; give the others an h estimate.
    3. Propagate the new information upward. Start a set S = {NODE}. Repeatedly take from S a node CURRENT none of whose descendants are still in S, and:
      • compute the cost of every arc leaving CURRENT: the sum over its successors of (edge cost + h(successor));
      • set h(CURRENT) to the cheapest arc cost and mark that arc as the best one;
      • label CURRENT SOLVED if every successor on the marked arc is SOLVED;
      • if CURRENT became SOLVED or its h changed, add its parents to S.

When the loop ends with INIT SOLVED, the marked arcs from INIT form the solution graph.

Worked example with a step-by-step trace

A can be solved either through B, or through the AND arc (C AND D). B can be solved through E or F. C reduces to the terminal G; D reduces to the AND arc (I AND J), both terminal. Each edge costs 1.

                 A
            /         \
       (OR)            (AND arc)
         B             C ───── D
       /   \           |      /  \
      E     F          G     I    J
    h=7   h=9      (solved) (solved)(solved)

Initial estimates: h(B)=2, h(C)=1, h(D)=1. Every edge costs 1.
StepNode expandedWhat is learnedCost via BCost via C AND DMarked arc at A
1Ah(B)=2, h(C)=1, h(D)=11 + 2 = 3(1+1) + (1+1) = 4B
2BE costs 1+7=8, F costs 1+9=10, so h(B) = 81 + 8 = 94C AND D (switch)
3CC → G, G is solved: h(C) = 1, C SOLVED9(1+1) + (1+1) = 4C AND D
4DD → I AND J, both solved: h(D) = 2, D SOLVED9(1+1) + (1+2) = 5C AND D, A SOLVED

Step 2 is the important one. After expanding A, the branch through B looked cheapest (3). Expanding B showed it really costs at least 8, so the revised cost of A through B jumped to 9 and AO* moved its marked arc to the AND arc. Step 4 shows a smaller revision: D turned out to cost 2 rather than the estimated 1, so h(A) rose from 4 to 5. Since both C and D are now SOLVED, A is SOLVED and the search stops without ever expanding E or F.

Solution graph: A → (C AND D), C → G, D → (I AND J). Total cost: 5 edges = 5.

AO* in Python

This implementation follows the steps above for an acyclic AND-OR graph. Each node maps to a list of arcs, and each arc is a list of children: one child for an OR branch, several for an AND arc.

import math

# Each node maps to a list of arcs. An arc is a list of children:
# one child = OR branch, several children = AND arc (all must be solved).
graph = {
    'A': [['B'], ['C', 'D']],   # A can be solved via B, OR via (C AND D)
    'B': [['E'], ['F']],
    'C': [['G']],
    'D': [['I', 'J']],
}
h = {'A': 0, 'B': 2, 'C': 1, 'D': 1, 'E': 7, 'F': 9, 'G': 0, 'I': 0, 'J': 0}
terminal = {'G', 'I', 'J'}      # primitive problems, solved directly
EDGE_COST = 1

def ao_star(start):
    best, solved, expanded = {}, set(terminal), set()

    def revise(node):
        arcs = graph.get(node, [])
        if not arcs:                       # dead end: cannot be solved
            h[node] = math.inf
            return
        costs = [sum(EDGE_COST + h[c] for c in arc) for arc in arcs]
        i = costs.index(min(costs))
        h[node], best[node] = costs[i], arcs[i]
        if all(c in solved for c in arcs[i]):
            solved.add(node)

    def update(node, done):                # bottom-up cost revision
        for arc in graph.get(node, []):
            for c in arc:
                if c in expanded and c not in done:
                    update(c, done)
        revise(node)
        done.add(node)

    def pick(node):                        # unexpanded node on the current best graph
        if node in solved:
            return None
        if node not in expanded:
            return node
        for c in best.get(node, []):
            n = pick(c)
            if n:
                return n
        return None

    while start not in solved and h[start] < math.inf:
        node = pick(start)
        if node is None:
            break
        expanded.add(node)
        update(start, set())
        print(f"expand {node}: h(A) = {h[start]}, best arc at A = {best[start]}")
    return best

def solution(node, best, out):
    if node in best:
        out.append(f"{node} -> {' AND '.join(best[node])}")
        for c in best[node]:
            solution(c, best, out)
    return out

best = ao_star('A')
print("Solution graph:", "; ".join(solution('A', best, [])))
print("Cost:", h['A'])

Output:

expand A: h(A) = 3, best arc at A = ['B']
expand B: h(A) = 4, best arc at A = ['C', 'D']
expand C: h(A) = 4, best arc at A = ['C', 'D']
expand D: h(A) = 5, best arc at A = ['C', 'D']
Solution graph: A -> C AND D; C -> G; D -> I AND J
Cost: 5

The output matches the hand trace. update() does the upward propagation by revising children before parents, and pick() follows only the marked arcs, so nodes off the current best solution graph (E and F) are never expanded.

Properties of AO*

  • Admissibility: if h never overestimates the true cost of solving a node, and the graph has no cycles, AO* returns a minimum-cost solution graph. In the example, every initial estimate was at most the true cost.
  • Works on solution graphs, not paths: the cost of an AND arc is the sum over all its successors, while an OR choice takes the minimum.
  • Stops early: once the start node is SOLVED, AO* does not keep exploring other branches, which is why it can skip large parts of the graph.
  • Cycles need care: the standard version skips successors that are ancestors of the node being expanded; graphs with loops are not handled in general.
  • Interacting subgoals are ignored: AO* assumes the subproblems under an AND arc can be solved independently. If solving C changes how hard D is, the cost estimates are no longer valid.
PointA*AO*
Graph typeOR graph (alternatives only)AND-OR graph
ResultA single pathA solution graph or tree
Scoref(n) = g(n) + h(n) per pathRevised h at each node; AND = sum, OR = minimum
Cost revisionNot needed; g is known exactlyEssential; estimates propagate up after every expansion
Explores after a solution is found?Stops at the first goal it expandsStops when the start node is SOLVED

Where AND-OR search is used

  • Problem reduction and planning: breaking a goal into subgoals that must all be achieved, as in hierarchical task planning.
  • Theorem proving and rule-based reasoning: to prove a goal you may need to prove all premises of one rule (AND) or pick one of several rules (OR). Backward chaining in production systems builds exactly this kind of tree.
  • Games and decisions under uncertainty: your move is an OR choice, while every possible opponent reply or chance outcome must be handled, which is an AND. The minimax algorithm searches a similar two-level structure.

If you are coming to AO* from uninformed methods, BFS and DFS and best-first search are the natural steps before it, and heuristic search techniques explains how estimates like h(n) are designed. Heuristic search, including A* and AO*, is part of the problem-solving module in Uncodemy's Artificial Intelligence course.