Enumerate All Possible Tic-Tac-Toe Game Paths
Dynamic ProgrammingAuto-graded · 18 test casesLast updated
Tests recursive game-tree traversal with memoization to count distinct play sequences by outcome.
Problem Description
You are given a 3×3 Tic-Tac-Toe board (possibly in progress) and need to determine how many different ways the game can be completed from that position, categorized by who wins or whether it ends in a draw.
In Tic-Tac-Toe, two players—'X' and 'O'—take turns placing their mark in an empty cell. Player 'X' always goes first from an empty board. The game ends immediately when:
- One player forms three marks in a row (horizontally, vertically, or diagonally)—that player wins.
- All nine cells are filled with no winner—the game is a draw.
Important: Two game sequences are distinct if they differ in move order, even if they produce the same final board. For example, X placing marks at positions (0,0) then (0,1) is a different sequence than (0,1) then (0,0).
Your task is to count how many distinct complete game sequences exist from the given board state, broken down by outcome.
Function Signature
def enumerate_ttt_paths(
board: Optional[List[List[str]]] = None,
current_player: str = "X"
) -> Dict[str, int]:
Parameters
-
board: A 3×3 grid represented as a list of three lists, where each cell contains:'X'for an X mark'O'for an O mark'.'for an empty cell
If
boardisNone, the function starts from an empty 3×3 grid. -
current_player: Either'X'or'O', indicating whose turn it is. Defaults to'X'.
The input board is guaranteed to represent a valid, ongoing game state (not already won or full).
Return Value
A dictionary containing four keys:
'X': Count of distinct game sequences where X wins'O': Count of distinct game sequences where O wins'Draw': Count of distinct game sequences ending in a draw'Total': Sum of all three counts above
Constraints
- The board is always exactly 3×3
- The provided board state is always valid and non-terminal
- Your solution must compute the result algorithmically; hardcoded answers will be rejected
- Execution must complete within 2.0 seconds for an empty board
- Empty cells are represented by
'.'
Examples
Example 1
Input: enumerate_ttt_paths()
Output: {'X': 131184, 'O': 77904, 'Draw': 46080, 'Total': 255168}
Example 2
Input: enumerate_ttt_paths([['X', 'O', 'X'], ['X', 'O', 'O'], ['.', '.', '.']], 'X')
Output: {'X': 2, 'O': 1, 'Draw': 2, 'Total': 5}
Hints
Hint 1
Model this as a game tree where each node is a board state and edges represent legal moves. Count the paths from root to each type of leaf.
Hint 2
Memoization is key: the number of ways to complete a game from a given position depends only on that position and whose turn it is, not on how you arrived there.
Hint 3
Check for wins before checking if the board is full—a move that fills the last cell and completes three-in-a-row is a win, not a draw.
Worked solution
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Approach
This problem asks us to count every distinct sequence of moves that completes a Tic-Tac-Toe game from a given starting position. The key insight is that we can model the problem as traversing a game tree where:
- Each node represents a board state plus whose turn it is
- Each edge represents a legal move (placing a mark in an empty cell)
- Each leaf node is a terminal game state (win or draw)
- Each root-to-leaf path corresponds to one distinct game sequence
We use depth-first search with memoization to count these paths efficiently.
Why Memoization Works
Even though move order matters for counting distinct sequences, we can still memoize because: the number of ways to complete a game from position P depends only on P and whose turn it is, not on how we reached P.
When the same board state is reached via different move orders, each path that leads there will independently add the full subtree count to its parent. This ensures every distinct sequence is counted exactly once.
Algorithm Steps
- Convert the board to a hashable tuple of 9 cells (row-major order) so we can cache on board states
- Define the recursive function
count_paths(state, player):- Check for X win: if X has three in a row, return (1, 0, 0)
- Check for O win: if O has three in a row, return (0, 1, 0)
- Check for draw: if no empty cells remain, return (0, 0, 1)
- Recursive case: for each empty cell, place the current player's mark, recurse with the opponent's turn, and sum all the returned counts
- Start the recursion from the initial board state and current player
- Return the dictionary with X wins, O wins, draws, and their total
Critical Detail: Win Checks Before Full Board
We must check for wins before checking if the board is full. If a player's final move both fills the ninth cell and completes three-in-a-row, that's a win, not a draw.
Why It's Correct
- Each terminal state (win or draw) contributes exactly 1 to its category
- Each path through the game tree from root to leaf represents one unique move sequence
- Memoization changes only performance, not correctness—it returns the same counts that a naive recursion would, just faster
- From an empty board, this produces the well-known counts: 131,184 X wins, 77,904 O wins, 46,080 draws
Complexity
Let S be the number of reachable game states (at most 5,478 for Tic-Tac-Toe).
- Time: O(S × 9) — each state is visited once (due to memoization), and for each state we check up to 9 empty cells and 8 winning lines
- Space: O(S) for the memoization cache, plus O(9) recursion depth
Without memoization, the time would be exponential in the depth of the game tree, but still fast enough for a 3×3 board (~550k nodes).
Solution Code
from functools import lru_cache
from typing import Dict, List, Optional
def enumerate_ttt_paths(
board: Optional[List[List[str]]] = None,
current_player: str = "X"
) -> Dict[str, int]:
# Convert board to a hashable tuple for memoization
if board is None:
cells = tuple("." * 9)
else:
cells = tuple(cell for row in board for cell in row)
# All possible winning lines (rows, columns, diagonals)
win_lines = (
(0, 1, 2), (3, 4, 5), (6, 7, 8), # rows
(0, 3, 6), (1, 4, 7), (2, 5, 8), # columns
(0, 4, 8), (2, 4, 6), # diagonals
)
def has_won(state, player):
"""Check if the given player has three in a row."""
return any(
all(state[idx] == player for idx in line)
for line in win_lines
)
@lru_cache(maxsize=None)
def count_paths(state, player):
"""
Returns (x_wins, o_wins, draws) counting all completion paths
from this state with the given player to move.
"""
# Check terminal conditions: wins first, then full board
if has_won(state, "X"):
return (1, 0, 0)
if has_won(state, "O"):
return (0, 1, 0)
# Find empty cells
empty_cells = [i for i in range(9) if state[i] == "."]
if not empty_cells:
return (0, 0, 1) # Draw
# Recursively try each possible move
x_total, o_total, draw_total = 0, 0, 0
opponent = "O" if player == "X" else "X"
for cell_idx in empty_cells:
# Make the move
new_state = list(state)
new_state[cell_idx] = player
new_state = tuple(new_state)
# Recurse and accumulate counts
x_count, o_count, draw_count = count_paths(new_state, opponent)
x_total += x_count
o_total += o_count
draw_total += draw_count
return (x_total, o_total, draw_total)
x_wins, o_wins, draws = count_paths(cells, current_player)
return {
"X": x_wins,
"O": o_wins,
"Draw": draws,
"Total": x_wins + o_wins + draws
}