Alpha-Beta pruning is an optimization technique for the Minimax algorithm, primarily used in two-player, turn-based games like Chess, Checkers, or Tic-Tac-Toe. It significantly reduces the number of nodes evaluated in a search tree by "pruning" branches that cannot possibly influence the final decision.
In C#, you typically implement it recursively.
• Max node tries to maximize score
• Min node tries to minimize score
• Alpha = best value that MAX can guarantee so far
• Beta = best value that MIN can guarantee so far
• If alpha >= beta, we stop exploring that branch (prune)
Alpha-beta is much more efficient if you:
• Sort moves so best ones are searched first
• Good ordering can reduce complexity dramatically
Most real games:
• Don’t search full tree
• Use evaluation function at cutoff depth
• Minimax: O(b^d)
• Alpha-beta (best case): O(b^(d/2))
(b = branching factor, d = depth)
You need to define your game tree representation:
public class Node
{
public int Value; // for leaf nodes
public bool IsTerminal()
{
return Children == null || Children.Count == 0;
}
public List Children;
public List GetChildren()
{
return Children ?? new List();
}
public int Evaluate()
{
// Replace with your heuristic evaluation function
return Value;
}
}
using System;
using System.Collections.Generic;
public class AlphaBeta
{
public const int MAX_DEPTH = 5;
// Entry point
public int FindBestMove(Node root)
{
return AlphaBetaSearch(root, MAX_DEPTH, int.MinValue, int.MaxValue, true);
}
private int AlphaBetaSearch(Node node, int depth, int alpha, int beta, bool isMaximizing)
{
// Terminal condition (leaf or depth limit)
if (depth == 0 || node.IsTerminal())
{
return node.Evaluate();
}
if (isMaximizing)
{
int value = int.MinValue;
foreach (var child in node.GetChildren())
{
value = Math.Max(
value,
AlphaBetaSearch(child, depth - 1, alpha, beta, false)
);
alpha = Math.Max(alpha, value);
// Prune
if (alpha >= beta)
break;
}
return value;
}
else
{
int value = int.MaxValue;
foreach (var child in node.GetChildren())
{
value = Math.Min(
value,
AlphaBetaSearch(child, depth - 1, alpha, beta, true)
);
beta = Math.Min(beta, value);
// Prune
if (alpha >= beta)
break;
}
return value;
}
}
}