Minimax with alpha–beta pruning
The best move in a game tree: the players take turns maximizing and minimizing, and branches that cannot change the result are pruned.
In a two-player game, the maximizer wants a high score and the minimizer a low one. The game tree shows every move, and the leaves are the scores at the end of the game. Minimax works up from the leaves: the maximum of the children on a max level, the minimum on a min level.
Read the full explanation ↓- Time:
O(n) worst, about O(n^¾) with good ordering - Space:
O(log n) - Horowitz–Sahni, chapter 8
Eight leaves on three levels (max, min, max); two prunings happen and only 5 leaves are seen. The answer is 5.
INF = float("inf")def alpha_beta(leaves):return search(leaves, 0, len(leaves) - 1, True, -INF, INF)def search(leaves, lo, hi, maximizing, alpha, beta):if lo == hi:return leaves[lo]mid = (lo + hi) // 2if maximizing:best = search(leaves, lo, mid, False, alpha, beta)alpha = max(alpha, best)if alpha >= beta:return bestbest = max(best, search(leaves, mid + 1, hi, False, alpha, beta))return bestbest = search(leaves, lo, mid, True, alpha, beta)beta = min(beta, best)if alpha >= beta:return bestbest = min(best, search(leaves, mid + 1, hi, True, alpha, beta))return best
Start
Recursion tree
Filled orange = running call · Orange outline = still on the stack · Grey = finished
Local variables
Orange = changed in this step
leaves list
Call stack
- alpha_beta()line 4
Explanation
The idea
In a two-player game, the maximizer wants a high score and the minimizer a low one. The game tree shows every move, and the leaves are the scores at the end of the game. Minimax works up from the leaves: the maximum of the children on a max level, the minimum on a min level.
Here the array holds the leaves of a full binary tree: two moves per turn, with the maximizer moving first.
Alpha–beta pruning
α: the score the maximizer has guaranteed so far.β: the score the minimizer has guaranteed so far.
If α ≥ β somewhere, the opponent will never let the game reach this branch; so the remaining children are
pruned. The answer is exactly the minimax value, just found faster.
Move order
With a good order (best move first) the number of leaves looked at drops to about n^¾ (for a binary tree); with a
bad order nothing is saved.
What to watch in the trace
- The call tree is the game tree; the range
lo..hiunder the array is the current subtree. - Compare "a lucky order" with "an unlucky order" by how many leaves are looked at.