Minimax Game AI - Problem

Implement a minimax algorithm with alpha-beta pruning for Tic-Tac-Toe to create an unbeatable AI player.

The AI should analyze all possible future game states and choose the move that maximizes its chances of winning while minimizing the opponent's chances. Your implementation should include:

  • Minimax algorithm - recursively evaluate all possible moves
  • Alpha-beta pruning - optimize by cutting off branches that won't affect the final decision
  • Game state evaluation - determine if a position is winning, losing, or drawn

Given a Tic-Tac-Toe board state and whose turn it is, return the [row, col] coordinates of the best move for the current player.

Board representation: 3x3 matrix where 0 = empty, 1 = player 1 (maximizing), -1 = player 2 (minimizing)

Input & Output

Example 1 — Maximize Player Winning Move
$ Input: board = [[0,1,-1],[1,0,0],[0,0,0]], isMaximizing = true
Output: [0,0]
💡 Note: Player 1 (maximizing) can win by playing at [0,0], creating a diagonal: [1,1,-1],[1,0,0],[0,0,0] → three 1's diagonally
Example 2 — Minimize Player Blocking Move
$ Input: board = [[1,0,0],[0,1,0],[0,0,-1]], isMaximizing = false
Output: [2,2]
💡 Note: Player -1 (minimizing) must block the diagonal by playing at [2,2], preventing player 1 from getting three in a row
Example 3 — Late Game Optimal Move
$ Input: board = [[1,-1,1],[-1,1,-1],[0,1,0]], isMaximizing = true
Output: [2,0]
💡 Note: With limited moves left, player 1 chooses [2,0] as the best available option to maximize their position

Constraints

  • Board is 3×3 matrix with values: 0 (empty), 1 (player 1), -1 (player 2)
  • At least one empty cell exists (game not over)
  • Board state is valid (no illegal configurations)
  • isMaximizing indicates current player: true for player 1, false for player -1

Visualization

Tap to expand
INPUTGame Board State01-1100000Player Turn: Maximizing (1)Need to find winning moveALGORITHMMinimax + Alpha-BetaMAX+10-1PrunedAlpha-Beta Boundsα = -∞ → +1 (best for MAX)β = +∞ → 0 (best for MIN)O(b^(d/2)) complexityGuarantees optimal moveRESULTOptimal MoveMove:[0, 0]Winning diagonal moveCreates three 1s in diagonalUNBEATABLE AIPerfect play guaranteedKey Insight:Alpha-beta pruning eliminates branches that cannot improve the current best move,reducing search time from O(b^d) to O(b^(d/2)) while maintaining optimal results.TutorialsPoint - Minimax Game AI | Alpha-Beta Pruning
Asked in
Google 15 Amazon 12 Microsoft 18 Apple 8 Meta 10
23.5K Views
Medium Frequency
~45 min Avg. Time
890 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen