Minimax is a kind of backtracking algorithm that is used in decision making and game theory to find the optimal move for a player, assuming that your opponent also plays optimally.
Every board state has a value associated with it.
Since this is a backtracking based algorithm, it tries all possible moves, then backtracks and makes a decision.
A program to illustrate the Minimax Algorithm
A Tic-Tac-Toe example program to illustrate the Minimax Algorithm
function minimax(board, depth, isMaximizingPlayer): if current board state is a terminal state : return value of the board if isMaximizingPlayer : bestVal = -INFINITY for each move in board : value = minimax(board, depth+1, false) bestVal = max( bestVal, value) return bestVal else : bestVal = +INFINITY for each move in board : value = minimax(board, depth+1, true) bestVal = min( bestVal, value) return bestVal
Consider a game which has 4 final states and paths to reach final state are from root to 4 leaves of a perfect binary tree as shown below.
Since this is a backtracking based algorithm, it tries all possible moves, then backtracks and makes a decision.
Being the maximizer you would choose the larger value that is 3.
Now the game tree looks like below:
The above tree shows two possible scores when maximizer makes left and right moves.
NOTE: Even though there is a value of 9 on the right subtree, the minimizer will never pick that.