Count All Valid 4×4 Three-in-a-Row Game Sequences
Trees & GraphsModel answerLast updated
Use recursion and backtracking to enumerate every ordered move sequence on a 4×4 board where three consecutive marks (not four) wins.
The Problem
You have a blank 4×4 grid. Two players take turns placing their symbol — call them X and O — with X going first and the two strictly alternating. A player wins the moment they complete three of their own marks in a straight line (horizontal, vertical, or diagonal). On a 4×4 board a "line" means a length-3 window, so each row contains two such windows (positions 0–2 and 1–3), and so do columns and both main diagonals. The instant a win is achieved the game is over; no additional moves are played.
A game ends in one of three ways:
- X wins — X completes a length-3 line first.
- O wins — O completes a length-3 line first.
- Draw — every cell is filled and neither player has a three-in-a-row.
Write a function using recursion and backtracking that counts every distinct valid game sequence. Two play-throughs that reach the same final board state but via different move orders count as separate sequences.
def count_games() -> int:
"""Return the total number of valid ordered game sequences."""
...
Your solution should be capable of returning the count broken down by outcome (X wins, O wins, draws) if asked. You should also be prepared to discuss:
- Your choice of board representation and the trade-offs.
- How you detect wins efficiently without re-scanning the whole board.
- How backtracking keeps the board clean across recursive calls.
- The worst-case complexity and how the win-pruning helps in practice.
Constraints
- The grid is exactly 4×4 (16 cells).
- The win condition is three consecutive marks; four in a row contains two overlapping wins and also counts (the game would have stopped at three).
Xalways moves first; players strictly alternate.- Count ordered sequences (move order matters), not unique terminal board positions.
- A single-threaded solution is expected; you may discuss symmetry reduction or memoization as extensions.
Clarifying questions worth raising
- Does four consecutive marks trigger a win, or only exactly three? (Four contains a three-in-a-row sub-window, so most interpretations say yes — confirm.)
- Are we counting ordered play sequences or distinct board positions? (Changes the answer by orders of magnitude.)
- Do we need per-outcome counts or just the grand total?
- Should board symmetries (rotations and reflections) be collapsed into one, or treated as distinct games?
- Is the output a single integer, a generator, or the full list of move sequences?
Hints
Hint 1
A flat 16-element array is easier to mutate and restore than a 2D list, but either works — the key is that backtracking must undo every mutation before returning, so copy-on-every-call is wasteful here.
Hint 2
You don't need to scan all 24 windows after every move. Only lines that pass through the cell just played can be newly completed, so restrict your win check to the rows, columns, and diagonals that include that cell.
Hint 3
The raw upper bound on the search tree is 16! ≈ 2×10¹³, but the 'stop on win' rule prunes the tree heavily — most branches end well before all 16 cells are filled. Count sequences rather than materializing them to stay within memory.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Board representation
A flat list of 16 values (None, 'X', or 'O') indexed r*4 + c is the most convenient. Mutation-plus-undo (set cell, recurse, clear cell) avoids allocating a new board on every call and keeps memory usage proportional to the depth of the recursion stack (at most 16 frames).
Enumerating all length-3 windows
On a 4×4 grid the winning lines are all contiguous triples:
- Rows: 4 rows × 2 windows each = 8
- Columns: 4 columns × 2 windows each = 8
- Main diagonals (top-left to bottom-right): windows starting at (0,0), (0,1), (1,0), (1,1) = 4
- Anti-diagonals (top-right to bottom-left): same count = 4
Total: 24 lines. Precompute them once as a list of index triples.
Win detection
Rather than scanning all 24 lines after every move, filter to only the lines that include the cell just placed. With 24 lines and at most ~7 lines through any single cell, this check is O(1) in practice.
from itertools import product
def build_lines():
lines = []
# rows
for r in range(4):
for c in range(2):
lines.append((r*4+c, r*4+c+1, r*4+c+2))
# columns
for c in range(4):
for r in range(2):
lines.append((r*4+c, (r+1)*4+c, (r+2)*4+c))
# main diagonals
for r in range(2):
for c in range(2): # only (0,0),(0,1),(1,0),(1,1) fit
# wait — check: r+2 <= 3 and c+2 <= 3
lines.append((r*4+c, (r+1)*4+(c+1), (r+2)*4+(c+2)))
# anti-diagonals
for r in range(2):
for c in range(2, 4):
lines.append((r*4+c, (r+1)*4+(c-1), (r+2)*4+(c-2)))
return lines
LINES = build_lines() # 24 triples
# precompute which lines pass through each cell
from collections import defaultdict
CELL_LINES = defaultdict(list)
for line in LINES:
for idx in line:
CELL_LINES[idx].append(line)
def is_win(board, last_idx, player):
return any(
board[a] == board[b] == board[c] == player
for a, b, c in CELL_LINES[last_idx]
)
Recursive backtracking
def count_games():
board = [None] * 16
results = {'X': 0, 'O': 0, 'draw': 0}
def recurse(player, moves_made):
# try every empty cell
found_move = False
opponent = 'O' if player == 'X' else 'X'
for idx in range(16):
if board[idx] is not None:
continue
found_move = True
board[idx] = player # make move
if is_win(board, idx, player):
results[player] += 1 # terminal: win
elif moves_made + 1 == 16:
results['draw'] += 1 # terminal: draw
else:
recurse(opponent, moves_made + 1)
board[idx] = None # undo move
recurse('X', 0)
return results
Complexity
Upper bound: without any pruning, the tree has at most 16 × 15 × 14 × … = 16! ≈ 2 × 10¹³ leaves. That is the worst case if no game ever ends before all cells are filled — which cannot happen on this board.
With win-pruning: most branches terminate between move 5 (the earliest X can win) and move 16. Empirically, the actual count is in the hundreds of millions to low billions, and the tree runs in a matter of minutes on a single core in Python (seconds in C++). The exact figure depends on the win definition, which is why clarifying the rules up front matters.
Space: O(16) for the board plus O(16) for the call stack — effectively constant.
Common mistakes
- Scanning all 24 lines on every move instead of only lines through the last cell. It is correct but does unnecessary work in each frame.
- Forgetting anti-diagonals or the second window in each row/column. Sketch the 24 lines explicitly and verify the count before coding.
- Counting unique board positions instead of ordered sequences. The distinction is enormous — if you count unique boards you need to deduplicate, and the number is far smaller.
- Checking for a draw before checking for a win on the final move. A player can win by filling the last empty cell; the win check must come first.
- Not restoring the board after a terminal state. Even when the recursion does not go deeper, the
board[idx] = Noneundo must still execute unconditionally — put it after the if/elif/else block, not inside a branch.
Extensions worth mentioning
- Symmetry reduction: the 4×4 board has a dihedral group of 8 symmetries (4 rotations × 2 reflections). Canonicalizing the board at each node could reduce the tree by up to 8×, but verifying correctness requires multiplying back by the orbit size — non-trivial to get right.
- Bitmask representation: encode
XandOpositions as two 16-bit integers. Line checks become bitwise AND operations, which are faster but harder to read. - Parallelism: the 16 first moves are independent sub-trees that can be distributed across cores with no shared state beyond the final counter.