The Wayback Machine - https://web.archive.org/web/20240927193717/https://www.geeksforgeeks.org/minimax-algorithm-in-game-theory-set-1-introduction/
Open In App

Minimax Algorithm in Game Theory | Set 1 (Introduction)

Last Updated : 13 Jun, 2022
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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. It is widely used in two player turn-based games such as Tic-Tac-Toe, Backgammon, Mancala, Chess, etc.
In Minimax the two players are called maximizer and minimizer. The maximizer tries to get the highest score possible while the minimizer tries to do the opposite and get the lowest score possible.
Every board state has a value associated with it. In a given state if the maximizer has upper hand then, the score of the board will tend to be some positive value. If the minimizer has the upper hand in that board state then it will tend to be some negative value. The values of the board are calculated by some heuristics which are unique for every type of game.

Example: 
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. Assume you are the maximizing player and you get the first chance to move, i.e., you are at the root and your opponent at next level. Which move you would make as a maximizing player considering that your opponent also plays optimally?

Game Theory  Minimax Algorithm

Since this is a backtracking based algorithm, it tries all possible moves, then backtracks and makes a decision. 

  • Maximizer goes LEFT: It is now the minimizers turn. The minimizer now has a choice between 3 and 5. Being the minimizer it will definitely choose the least among both, that is 3
  • Maximizer goes RIGHT: It is now the minimizers turn. The minimizer now has a choice between 2 and 9. He will choose 2 as it is the least among the two values.

Being the maximizer you would choose the larger value that is 3. Hence the optimal move for the maximizer is to go LEFT and the optimal value is 3.

Now the game tree looks like below :

Game Theory Minimax Algorithm1

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. We must always assume that our opponent plays optimally.

Below is the implementation for the same. 

C++




// A simple C++ program to find
// maximum score that
// maximizing player can get.
#include<bits/stdc++.h>
using namespace std;
 
// Returns the optimal value a maximizer can obtain.
// depth is current depth in game tree.
// nodeIndex is index of current node in scores[].
// isMax is true if current move is
// of maximizer, else false
// scores[] stores leaves of Game tree.
// h is maximum height of Game tree
int minimax(int depth, int nodeIndex, bool isMax,
            int scores[], int h)
{
    // Terminating condition. i.e
    // leaf node is reached
    if (depth == h)
        return scores[nodeIndex];
 
    //  If current move is maximizer,
    // find the maximum attainable
    // value
    if (isMax)
       return max(minimax(depth+1, nodeIndex*2, false, scores, h),
            minimax(depth+1, nodeIndex*2 + 1, false, scores, h));
 
    // Else (If current move is Minimizer), find the minimum
    // attainable value
    else
        return min(minimax(depth+1, nodeIndex*2, true, scores, h),
            minimax(depth+1, nodeIndex*2 + 1, true, scores, h));
}
 
// A utility function to find Log n in base 2
int log2(int n)
{
  return (n==1)? 0 : 1 + log2(n/2);
}
 
// Driver code
int main()
{
    // The number of elements in scores must be
    // a power of 2.
    int scores[] = {3, 5, 2, 9, 12, 5, 23, 23};
    int n = sizeof(scores)/sizeof(scores[0]);
    int h = log2(n);
    int res = minimax(0, 0, true, scores, h);
    cout << "The optimal value is : " << res << endl;
    return 0;
}


Java




// A simple java program to find maximum score that
// maximizing player can get.
 
import java.io.*;
 
class GFG {
   
 
// Returns the optimal value a maximizer can obtain.
// depth is current depth in game tree.
// nodeIndex is index of current node in scores[].
// isMax is true if current move is of maximizer, else false
// scores[] stores leaves of Game tree.
// h is maximum height of Game tree
 static int minimax(int depth, int nodeIndex, boolean  isMax,
            int scores[], int h)
{
    // Terminating condition. i.e leaf node is reached
    if (depth == h)
        return scores[nodeIndex];
 
    // If current move is maximizer, find the maximum attainable
    // value
    if (isMax)
    return Math.max(minimax(depth+1, nodeIndex*2, false, scores, h),
            minimax(depth+1, nodeIndex*2 + 1, false, scores, h));
 
    // Else (If current move is Minimizer), find the minimum
    // attainable value
    else
        return Math.min(minimax(depth+1, nodeIndex*2, true, scores, h),
            minimax(depth+1, nodeIndex*2 + 1, true, scores, h));
}
 
// A utility function to find Log n in base 2
 static int log2(int n)
{
return (n==1)? 0 : 1 + log2(n/2);
}
 
// Driver code
 
    public static void main (String[] args) {
            // The number of elements in scores must be
    // a power of 2.
    int scores[] = {3, 5, 2, 9, 12, 5, 23, 23};
    int n = scores.length;
    int h = log2(n);
    int res = minimax(0, 0, true, scores, h);
    System.out.println( "The optimal value is : "  +res);
         
    }
}
 
// This code is contributed by vt_m


C#




// A simple C# program to find maximum score that
// maximizing player can get.
using System;
 
public class GFG
{
     
// Returns the optimal value a maximizer can obtain.
// depth is current depth in game tree.
// nodeIndex is index of current node in scores[].
// isMax is true if current move is of maximizer, else false
// scores[] stores leaves of Game tree.
// h is maximum height of Game tree
static int minimax(int depth, int nodeIndex, bool isMax,
            int []scores, int h)
{
    // Terminating condition. i.e leaf node is reached
    if (depth == h)
        return scores[nodeIndex];
 
    // If current move is maximizer, find the maximum attainable
    // value
    if (isMax)
    return Math.Max(minimax(depth+1, nodeIndex*2, false, scores, h),
            minimax(depth+1, nodeIndex*2 + 1, false, scores, h));
 
    // Else (If current move is Minimizer), find the minimum
    // attainable value
    else
        return Math.Min(minimax(depth+1, nodeIndex*2, true, scores, h),
            minimax(depth+1, nodeIndex*2 + 1, true, scores, h));
}
 
// A utility function to find Log n in base 2
static int log2(int n)
{
    return (n==1)? 0 : 1 + log2(n/2);
}
 
// Driver code
static public void Main ()
{
 
    // The number of elements in scores must be
    // a power of 2.
    int []scores = {3, 5, 2, 9, 12, 5, 23, 23};
    int n = scores.Length;
    int h = log2(n);
    int res = minimax(0, 0, true, scores, h);
    Console.WriteLine( "The optimal value is : " +res);
     
}
}
 
// This code is contributed by ajit.


Python3




# A simple Python3 program to find
# maximum score that
# maximizing player can get
import math
 
def minimax (curDepth, nodeIndex,
             maxTurn, scores,
             targetDepth):
 
    # base case : targetDepth reached
    if (curDepth == targetDepth):
        return scores[nodeIndex]
     
    if (maxTurn):
        return max(minimax(curDepth + 1, nodeIndex * 2,
                    False, scores, targetDepth),
                   minimax(curDepth + 1, nodeIndex * 2 + 1,
                    False, scores, targetDepth))
     
    else:
        return min(minimax(curDepth + 1, nodeIndex * 2,
                     True, scores, targetDepth),
                   minimax(curDepth + 1, nodeIndex * 2 + 1,
                     True, scores, targetDepth))
     
# Driver code
scores = [3, 5, 2, 9, 12, 5, 23, 23]
 
treeDepth = math.log(len(scores), 2)
 
print("The optimal value is : ", end = "")
print(minimax(0, 0, True, scores, treeDepth))
 
# This code is contributed
# by rootshadow


Javascript




<script>
 
// Javascript program to find maximum score that
// maximizing player can get.
 
// Returns the optimal value a maximizer can obtain.
// depth is current depth in game tree.
// nodeIndex is index of current node in scores[].
// isMax is true if current move is of maximizer, else false
// scores[] stores leaves of Game tree.
// h is maximum height of Game tree
 function minimax(depth, nodeIndex, isMax,
            scores, h)
{
    // Terminating condition. i.e leaf node is reached
    if (depth == h)
        return scores[nodeIndex];
   
    // If current move is maximizer, find the maximum attainable
    // value
    if (isMax)
    return Math.max(minimax(depth+1, nodeIndex*2, false, scores, h),
            minimax(depth+1, nodeIndex*2 + 1, false, scores, h));
   
    // Else (If current move is Minimizer), find the minimum
    // attainable value
    else
        return Math.min(minimax(depth+1, nodeIndex*2, true, scores, h),
            minimax(depth+1, nodeIndex*2 + 1, true, scores, h));
}
   
// A utility function to find Log n in base 2
 function log2(n)
{
return (n==1)? 0 : 1 + log2(n/2);
}
   
 
// Driver Code
 
    // The number of elements in scores must be
    // a power of 2.
    let scores = [3, 5, 2, 9, 12, 5, 23, 23];
    let n = scores.length;
    let h = log2(n);
    let res = minimax(0, 0, true, scores, h);
    document.write( "The optimal value is : "  +res);
         
                       
</script>


Output: 

The optimal value is:  12

Time complexity : O(b^d) b is the branching factor and d is count of depth or ply of graph or tree.

Space Complexity : O(bd) where b is branching factor into d is maximum depth of tree similar to DFS.

The idea of this article is to introduce Minimax with a simple example. 

  • In the above example, there are only two choices for a player. In general, there can be more choices. In that case, we need to recur for all possible moves and find the maximum/minimum. For example, in Tic-Tac-Toe, the first player can make 9 possible moves.
  • In the above example, the scores (leaves of Game Tree) are given to us. For a typical game, we need to derive these values

We will soon be covering Tic Tac Toe with Minimax algorithm.
This article is contributed by Akshay L. Aradhya.

 



Previous Article
Next Article

Similar Reads

Introduction to Evaluation Function of Minimax Algorithm in Game Theory
Prerequisite: Minimax Algorithm in Game TheoryAs seen in the above article, each leaf node had a value associated with it. We had stored this value in an array. But in the real world when we are creating a program to play Tic-Tac-Toe, Chess, Backgammon, etc. we need to implement a function that calculates the value of the board depending on the pla
8 min read
Minimax Algorithm in Game Theory | Set 4 (Alpha-Beta Pruning)
Prerequisites: Minimax Algorithm in Game Theory, Evaluation Function in Game TheoryAlpha-Beta pruning is not actually a new algorithm, but rather an optimization technique for the minimax algorithm. It reduces the computation time by a huge factor. This allows us to search much faster and even go into deeper levels in the game tree. It cuts off bra
11 min read
Minimax Algorithm in Game Theory | Set 5 (Zobrist Hashing)
Previous posts on this topic : Minimax Algorithm in Game Theory, Evaluation Function in Game Theory, Tic-Tac-Toe AI – Finding optimal move, Alpha-Beta Pruning.Zobrist Hashing is a hashing function that is widely used in 2 player board games. It is the most common hashing function used in transposition table. Transposition tables basically store the
12 min read
Finding optimal move in Tic-Tac-Toe using Minimax Algorithm in Game Theory
Prerequisites: Minimax Algorithm in Game Theory, Evaluation Function in Game TheoryLet us combine what we have learnt so far about minimax and evaluation function to write a proper Tic-Tac-Toe AI (Artificial Intelligence) that plays a perfect game. This AI will consider all possible scenarios and makes the most optimal move. Finding the Best Move :
15+ min read
Game Theory (Normal form game) | Set 2 (Game with Pure Strategy)
Game Theory (Normal – form game) | Set 1 (Introduction) Please go through the above article before proceeding. Given a payoff matrix. The task is to find the optimum strategies of the players. Solution: Player A is having 3 strategies - 1, 2 and 3, and player B is also having 3 strategies - 1, 2 and 3. Step 1: Find row minimum values for each row a
2 min read
Game Theory (Normal-form game) | Set 3 (Game with Mixed Strategy)
Consider the following payoff matrix with respect to player A and solve it optimally. Solution: If a game has no saddle point then the game is said to have mixed strategy. Step 1: Find out the row minimum and column maximum. Step 2: Find out the minimax and maximin values. Since minimax and maximin value of this game are not equal, this game has no
4 min read
Game Theory (Normal-form Game) | Set 7 (Graphical Method [M X 2] Game)
The payoff matrix of an M * 2 game consists of M rows and two columns. This article will discuss how to solve an M * 2 game by graphical method. Also, this article will discuss if more than two lines intersect the same point in the graph then how can a 2 * 2 payoff matrix be formed. Consider the below problem: Solution: First check whether the prob
3 min read
Game Theory (Normal-form Game) | Set 6 (Graphical Method [2 X N] Game)
The payoff matrix of a 2 * N game consists of 2 rows and N columns . This article will discuss how to solve a 2 * N game by graphical method. Consider the below 2 * 5 game: Solution: First check the saddle point of the game. This game has no saddle point. Step 1: Reduce the size of the payoff matrix by applying dominance property, if it exists. Thi
3 min read
Game Theory (Normal - form game) | Set 1 (Introduction)
Game theory is a mathematical model used for decision making. It has applications in all fields of social science, as well as in logic and computer science. Game theory has come to play an increasingly important role in logic and in computer science. To be fully defined, a game must specify the following elements: the players of the game, the infor
4 min read
Game Theory (Normal-form Game) | Set 5 (Dominance Property-Mixed Strategy)
This article discusses how to solve a game by the dominance property with mixed strategy. Consider the below game: Solution: Find out the row minimum and column maximum values. Here Minimax value is not equal to Maximin so this game has no saddle point. Now proceed with dominance property to reduce the rows and the columns. Reducing the row and the
2 min read
Combinatorial Game Theory | Set 2 (Game of Nim)
We strongly recommend to refer below article as a prerequisite of this. Combinatorial Game Theory | Set 1 (Introduction) In this post, Game of Nim is discussed. The Game of Nim is described by the following rules- “ Given a number of piles in which each pile contains some numbers of stones/coins. In each turn, a player can choose only one pile and
15+ min read
Game Theory (Normal-form Game) | Set 4 (Dominance Property-Pure Strategy)
In some of the games, it is possible to reduce the size of the payoff matrix by eliminating rows (or columns) that are dominated by other rows (or columns) respectively. Dominance property for rows: X ≤ Y i.e. if all the elements of a particular row X are less than or equal to the corresponding elements of another row Y then delete row X (row X is
4 min read
Combinatorial Game Theory | Set 1 (Introduction)
Combinatorial games are two-person games with perfect information and no chance moves (no randomization like coin toss is involved that can effect the game). These games have a win-or-lose or tie outcome and determined by a set of positions, including an initial position, and the player whose turn it is to move. Play moves from one position to anot
3 min read
Expectimax Algorithm in Game Theory
The Expectimax search algorithm is a game theory algorithm used to maximize the expected utility. It is a variation of the Minimax algorithm. While Minimax assumes that the adversary(the minimizer) plays optimally, the Expectimax doesn't. This is useful for modelling environments where adversary agents are not optimal, or their actions are based on
8 min read
Combinatorial Game Theory | Set 3 (Grundy Numbers/Numbers and Mex)
We have introduced Combinatorial Game Theory in Set 1 and discussed Game of Nim in Set 2.Grundy Number is a number that defines a state of a game. We can define any impartial game (example : nim game) in terms of Grundy Number. Grundy Numbers or Numbers determine how any Impartial Game (not only the Game of Nim) can be solved once we have calculate
15+ min read
Combinatorial Game Theory | Set 4 (Sprague - Grundy Theorem)
Prerequisites : Grundy Numbers/Numbers and MexWe have already seen in Set 2 (https://www.cdn.geeksforgeeks.org/combinatorial-game-theory-set-2-game-nim/), that we can find who wins in a game of Nim without actually playing the game.Suppose we change the classic Nim game a bit. This time each player can only remove 1, 2 or 3 stones only (and not any
15 min read
Pareto Optimality and its application in Game Theory
Prerequisites: Game Theory When the strategies from game theory are discussed, they are often mentioned from a player's perspective. However, when the strategies are formed from an observer's angle whose main motive is to wish for the best outcome for every player; that is, when strategies are formed from a socially balanced viewpoint, then the out
5 min read
Practice Problems on Game Theory
Game Theory is a topic in competitive programming that involves a certain type of problem, where there are some players who play a game based on given rules and the task is often to find the winner or the winning moves. Game Theory is often asked in short contests with a mixture of other topics like range querying or greedy or dynamic programming.
4 min read
The prisoner's dilemma in Game theory
Two members of a criminal gang are arrested and imprisoned. Each prisoner is in solitary confinement with no means of communicating with the other. The prosecutors lack sufficient evidence to convict the pair on the principal charge. They hope to get both sentenced to a year in prison on a lesser charge. Simultaneously, the prosecutors offer each p
3 min read
Dynamic Programming in Game Theory for Competitive Programming
In the fast-paced world of competitive programming, mastering dynamic programming in game theory is the key to solving complex strategic challenges. This article explores how dynamic programming in game theory can enhance your problem-solving skills and strategic insights, giving you a competitive edge. Whether you're a seasoned coder or a newcomer
15+ min read
Game Theory
Game Theory is a topic in competitive programming that involves a certain type of problem, where there are some players who play a game based on given rules and the task is often to find the winner or the winning moves. Game Theory is often asked in short contests with a mixture of other topics like range querying or greedy or dynamic programming.
15+ min read
Winning Game by replacing numbers with factors (Brain Game)
Given 2 players A and B take turns alternatively to play a game in which they have N numbers on a paper. In one turn, a player can replace one of the numbers by any of its factors (except for 1 & the number itself). The player who is unable to make a move loses the game. Find the winner of the game if A starts the game and both play optimally.
15+ min read
Game of Chocolates | Wythoff's Game
Bunty and Dolly are playing a game, described as follows:There are two boxes having A and B number of chocolates respectively. Both can eat L (L >= 1) chocolates from any one box or L chocolates from both boxes in one move. They play the game alternatively and the last one to eat the chocolate will be the winner. You have to help Bunty in decidi
13 min read
Hopcroft–Karp Algorithm for Maximum Matching | Set 1 (Introduction)
A matching in a Bipartite Graph is a set of the edges chosen in such a way that no two edges share an endpoint. A maximum matching is a matching of maximum size (maximum number of edges). In a maximum matching, if any edge is added to it, it is no longer a matching. There can be more than one maximum matching for a given Bipartite Graph. We have di
3 min read
MO's Algorithm (Query Square Root Decomposition) | Set 1 (Introduction)
Let us consider the following problem to understand MO's Algorithm.We are given an array and a set of query ranges, we are required to find the sum of every query range. Example: Input: arr[] = {1, 1, 2, 1, 3, 4, 5, 2, 8}; query[] = [0, 4], [1, 3] [2, 4] Output: Sum of arr[] elements in range [0, 4] is 8 Sum of arr[] elements in range [1, 3] is 4 S
15+ min read
Introduction to Disjoint Set (Union-Find Algorithm)
What is a Disjoint set data structure?Two sets are called disjoint sets if they don't have any element in common, the intersection of sets is a null set. A data structure that stores non overlapping or disjoint subset of elements is called disjoint set data structure. The disjoint set data structure supports following operations: Adding new sets to
15+ min read
Hungarian Algorithm for Assignment Problem | Set 1 (Introduction)
Let there be n agents and n tasks. Any agent can be assigned to perform any task, incurring some cost that may vary depending on the agent-task assignment. It is required to perform all tasks by assigning exactly one agent to each task and exactly one task to each agent in such a way that the total cost of the assignment is minimized. Example: You
15+ min read
Game Development with Unity | Introduction
Game Development: The article "Do you want to make your own games?" introducing the basic concept of game development. As mentioned in the article, Unity is one of the most popular game engines for both 2D and 3D games. You don't need to have a strong understanding of physics or mathematics to develop games. The game engine takes care of most of th
3 min read
Proof that Independent Set in Graph theory is NP Complete
Prerequisite: NP-Completeness, Independent set. An Independent Set S of graph G = (V, E) is a set of vertices such that no two vertices in S are adjacent to each other. It consists of non- adjacent vertices. Problem: Given a graph G(V, E) and an integer k, the problem is to determine if the graph contains an independent set of vertices of size >
5 min read
Mathematics | Graph Theory Basics - Set 1
A graph is a data structure that is defined by two components : A node or a vertex.An edge E or ordered pair is a connection between two nodes u,v that is identified by unique pair(u,v). The pair (u,v) is ordered because (u,v) is not same as (v,u) in case of directed graph.The edge may have a weight or is set to one in case of unweighted graph.Cons
4 min read
Article Tags :
Practice Tags :