KatInterview

Minimax Solver for 3×3 Tic-Tac-Toe with Optimal Move Selection

Trees & GraphsAuto-graded · 20 test cases
MediumAuto-gradedTrees & Graphsrecursionbacktrackinggame-theory

Last updated

Implement a recursive game-tree solver that finds the outcome under optimal play and identifies a winning or drawing move for the current player.

Implement a recursive game-tree solver for 3×3 tic-tac-toe that evaluates a given position assuming both players make optimal decisions.

You are given a board represented as a list of three strings, where each string contains exactly three characters. Each character is either 'X', 'O', or '.' (representing an empty cell). Row index 0 corresponds to the top row, and column index 0 corresponds to the leftmost column.

The game follows standard rules:

  • X always makes the first move in a fresh game
  • The current player is X when both marks appear equally often on the board, and O when X has one more mark than O
  • A player wins by placing three of their marks in any row, column, or diagonal
  • The game ends immediately when a player wins or when all nine cells are filled

Your function must determine two things:

  1. The outcome of the game when both players play optimally from the current position forward
  2. A move for the current player that achieves this outcome

Return a tuple (outcome, move) where:

  • outcome is the string "X" if X wins with optimal play, "O" if O wins with optimal play, or "draw" if neither player can force a win
  • move is a tuple (row, col) indicating an empty cell where the current player should place their mark to achieve the stated outcome, or None if the game has already ended

Use backtracking: recursively try each possible move, explore all resulting positions, then undo the move before trying the next option.

When multiple moves achieve the same optimal outcome, return the first one encountered when scanning the board from left to right, top to bottom (row 0 before row 1, and within each row, column 0 before column 1, etc.).

Constraints

  • The board is 3×3 (three strings of three characters each)
  • Each cell contains 'X', 'O', or '.'
  • You may assume the position is reachable through legal play
  • When multiple moves achieve the optimal outcome, return the lexicographically smallest (row, col) pair
  • 0 ≤ row, col ≤ 2

Examples

Example 1

Input: solve_tic_tac_toe(['XX.', 'OO.', '...'])

Output: ['X', [0, 2]]

Example 2

Input: solve_tic_tac_toe(['...', '...', '...'])

Output: ['draw', [0, 0]]

Hints

Hint 1

Check for wins by examining all eight possible lines: three rows, three columns, and two diagonals.

Hint 2

Use recursion where X tries to maximize the outcome score and O tries to minimize it, alternating turns after each move.

Hint 3

Remember to restore the board state after exploring each move by setting the cell back to '.' before trying the next option.