
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Minimax Algorithm with Alpha-Beta Pruning in C++
Description
Aplha-Beta pruning is a optimization technique used in minimax algorithm. The idea benind this algorithm is cut off the branches of game tree which need not to be evaluated as better move exists already.
This algorithm introduces two new fields −
- Alpha − This is best value(maximum) that maximizer player can guaratee at current level or its above level
- Beta − This is the best value(minimum) that minimizer player can guaratee at the current level or its above level.
Example
If game tree is −
arr [] = {13, 8, 24, -5, 23, 15, -14, -20}
then optimal value will be 13 if maximizer plays first
Algorithm
1. Start DFS traversal from the root of game tree 2. Set initial values of alpha and beta as follows: a. alpha = INT_MIN(-INFINITY) b. beta = INT_MAX(+INFINITY) 3. Traverse tree in DFS fashion where maximizer player tries to get the highest score possible while the minimizer player tries to get the lowest score possible. 4. While traversing update the alpha and beta values accordingly
Example
#include <iostream> #include <algorithm> #include <cmath> #include <climits> #define SIZE(arr) (sizeof(arr) / sizeof(arr[0])) using namespace std; int getHeight(int n) { return (n == 1) ? 0 : 1 + log2(n / 2); } int minmax(int height, int depth, int nodeIndex, bool maxPayer, int values[], int alpha, int beta) { if (depth == height) { return values[nodeIndex]; } if (maxPayer) { int bestValue = INT_MIN; for (int i = 0; i < height - 1; i++) { int val = minmax(height, depth + 1, nodeIndex * 2 + i, false, values, alpha, beta); bestValue = max(bestValue, val); alpha = max(alpha, bestValue); if (beta <= alpha) break; } return bestValue; } else { int bestValue = INT_MAX; for (int i = 0; i < height - 1; i++) { int val = minmax(height, depth + 1, nodeIndex * 2 + i, true, values, alpha, beta); bestValue = min(bestValue, val); beta = min(beta, bestValue); if (beta <= alpha) break; } return bestValue; } } int main() { int values[] = {13, 8, 24, -5, 23, 15, -14, -20}; int height = getHeight(SIZE(values)); int result = minmax(height, 0, 0, true, values, INT_MIN, INT_MAX); cout <<"Result : " << result << "\n"; return 0; }
When you compile and execute above program. It generates following output −
Result : 13
Advertisements