Minimax Solver for 3×3 Tic-Tac-Toe with Optimal Move Selection
Trees & GraphsAuto-graded · 20 test casesLast 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:
- The outcome of the game when both players play optimally from the current position forward
- A move for the current player that achieves this outcome
Return a tuple (outcome, move) where:
outcomeis the string"X"if X wins with optimal play,"O"if O wins with optimal play, or"draw"if neither player can force a winmoveis a tuple(row, col)indicating an empty cell where the current player should place their mark to achieve the stated outcome, orNoneif 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.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
This problem requires exploring the game tree using minimax search with backtracking. The core idea is to recursively evaluate every possible continuation of the game, assuming both players make their best moves.
We represent outcomes numerically: +1 for an X win, -1 for an O win, and 0 for a draw. Player X seeks to maximize this score, while player O seeks to minimize it.
The algorithm works as follows:
- Flatten the board into a single list for easier indexing and manipulation
- Detect terminal states by checking all eight lines (three rows, three columns, two diagonals) for three matching marks, and checking if the board is full
- Identify the current player by counting marks: if X and O have equal counts, X moves next; otherwise O moves next
- Handle finished games by returning the winner or draw immediately with no move
- Search recursively for each empty cell:
- Place the current player's mark
- Recursively evaluate the resulting position with the opponent to move
- Remove the mark (backtrack)
- Track the best score and corresponding move
- Return the outcome and move that achieves the best result for the current player
The search alternates between maximizing (for X) and minimizing (for O) at each level. X picks the move with the highest score, while O picks the move with the lowest score. When iterating through cells in order, we naturally return the first move that achieves the optimal score.
Correctness
The algorithm is correct because it exhaustively explores all legal continuations from the current position. By trying every empty cell as the next move and recursively evaluating the resulting positions, we guarantee finding the true minimax value of the position. The backtracking ensures the board state is properly restored between trials. The left-to-right, top-to-bottom iteration order ensures consistent tie-breaking.
Complexity
Time complexity: O(9!) in the worst case for the initial empty board, but typically much less due to early termination on wins. The branching factor decreases as cells are filled. For a 3×3 board, the search tree has at most a few hundred thousand nodes, which completes instantly.
Space complexity: O(9) for the recursion depth, which is bounded by the number of empty cells.
The search can be significantly optimized with memoization or alpha-beta pruning, but for 3×3 tic-tac-toe, the naive backtracking approach is fast enough.
from typing import List, Optional, Tuple
def solve_tic_tac_toe(board: List[str]) -> Tuple[str, Optional[Tuple[int, int]]]:
cells = [ch for row in board for ch in row]
lines = (
(0, 1, 2), (3, 4, 5), (6, 7, 8),
(0, 3, 6), (1, 4, 7), (2, 5, 8),
(0, 4, 8), (2, 4, 6),
)
def winner():
for a, b, c in lines:
if cells[a] != '.' and cells[a] == cells[b] == cells[c]:
return cells[a]
return None
def search(player):
won = winner()
if won == 'X':
return 1
if won == 'O':
return -1
if '.' not in cells:
return 0
scores = []
for i, cell in enumerate(cells):
if cell == '.':
cells[i] = player
scores.append(search('O' if player == 'X' else 'X'))
cells[i] = '.'
return max(scores) if player == 'X' else min(scores)
player = 'X' if cells.count('X') == cells.count('O') else 'O'
won = winner()
if won is not None:
return (won, None)
if '.' not in cells:
return ('draw', None)
best_score = -2 if player == 'X' else 2
best_move = None
for i, cell in enumerate(cells):
if cell == '.':
cells[i] = player
score = search('O' if player == 'X' else 'X')
cells[i] = '.'
if (player == 'X' and score > best_score) or (player == 'O' and score < best_score):
best_score = score
best_move = (i // 3, i % 3)
result = 'X' if best_score == 1 else 'O' if best_score == -1 else 'draw'
return (result, best_move)