function alphaBeta(node: Node, depth: number, alpha: number, beta: number, maximizing: boolean): number {if (depth === 0 || node.isLeaf) return node.value;
let best = maximizing ? -Infinity : Infinity;
for (const child of node.children) {const value = alphaBeta(child, depth - 1, alpha, beta, !maximizing);
best = maximizing ? Math.max(best, value) : Math.min(best, value);
if (maximizing) alpha = Math.max(alpha, best); else beta = Math.min(beta, best);
if (beta <= alpha) break;
}
return best;
}
Enter a MAX node at depth 0 with α = −∞, β = +∞.
Understanding Alpha-beta pruning
The idea
Alpha-beta is minimax that remembers two bounds while it searches: α, the best value MAX is already guaranteed somewhere above, and β, the best MIN is guaranteed. When a node finds a child that makes its own value worse than what the opponent can already force elsewhere, the remaining children cannot change the result and are skipped.
The answer is exactly the minimax value; only the work changes. With children in random order it roughly halves the leaves; with the best move tried first it visits about b^(d/2) leaves, which doubles the depth an engine can reach in the same time.
The four stages
Complexity
Versus its siblings
Pseudocode
ALPHABETA(node, depth, α, β, maximizing)
if depth = 0 or node is a leaf: return value(node)
best ← −∞ if maximizing else +∞
for each child of node
value ← ALPHABETA(child, depth − 1, α, β, not maximizing)
best ← max/min(best, value); α ← max(α, best) if maximizing else β ← min(β, best)
if β ≤ α: break
return best
When to use
Pitfalls
History
Alpha-beta was discovered several times: John McCarthy sketched it in 1956, Arthur Samuel used it in his checkers program, and Alexander Brudno published the first analysis in 1963. Donald Knuth and Ronald Moore proved its b^(d/2) bound in 1975, and every chess engine since has been built on it.