Minimax Algorithm in Game Theory | Set 1 (Introduction) (original) (raw)

Last Updated : 27 May, 2026

Minimax is a backtracking-based algorithm used in game theory and AI to determine the optimal move in competitive games by evaluating all possible future outcomes, assuming both players act optimally.

**Key Concepts

Working

2056958109

Working of Minimax Algorithm

Implementation

Implementing the Minimax algorithm using a simple game tree where leaf nodes represent final scores, and the algorithm finds the optimal value assuming both players play optimally.

**Step 1: Importing Required Module

Using the math module to compute the depth of the game tree.

Python `

import math

`

**Step 2: Defining Minimax Function

This function recursively evaluates the game tree and returns the optimal value based on maximizing and minimizing turns.

Python `

def minimax(curDepth, nodeIndex, maxTurn, scores, targetDepth):

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)
    )

`

**Step 3: Defining game states

We define leaf node values representing final game outcomes.

Python `

scores = [3, 5, 2, 9, 12, 5, 23, 23]

`

**Step 4: Computing the tree depth

Calculating the depth of the binary game tree using logarithm.

Python `

treeDepth = int(math.log(len(scores), 2))

`

**Step 5: Run the Minimax algorithm

We start evaluation from the root node assuming the maximizer plays first.

Python `

print("The optimal value is:", minimax(0, 0, True, scores, treeDepth))

`

**Output:

The optimal value is: 12

**Advantages

**Limitations