Algorithms · Visualized

Game: Tic-Tac-Toe Solver

Game Theory & Minimax

Two-player games — who wins with perfect play, and by how much.

Determines the optimal move (or the game's outcome with perfect play) using the Minimax algorithm: it explores every possible sequence of future moves, assuming both players play optimally — the maximizing player picks moves that lead to the best outcome for them, while the minimizing player picks moves that lead to the worst outcome for the maximizer. Time: O(b^d) average, O(9!) ≈ O(b^d), where b = branching factor (available moves), d = remaining depth — tiny for tic-tac-toe's small board worst; space: O(d) — recursion depth, at most 9 for tic-tac-toe.

Big-O: Winning positions, DP over states, and minimax evaluation.

Tic-Tac-Toe Solver

Game Theory / Minimax

Determines the optimal move (or the game's outcome with perfect play) using the Minimax algorithm: it explores every possible sequence of future moves, assuming both players play optimally — the maximizing player picks moves that lead to the best outcome for them, while the minimizing player picks moves that lead to the worst outcome for the maximizer.

How Tic-Tac-Toe Solver Works

  1. If the current board is a terminal state (someone has won, or the board is full/draw), return a score representing that outcome (e.g. +1 for a maximizer win, -1 for a minimizer win, 0 for a draw).
  2. Otherwise, generate all possible moves (empty cells) from the current board state.
  3. For each possible move, recursively call minimax on the resulting board, with the roles swapped (it becomes the other player's turn).
  4. If it's the maximizing player's turn, pick the move with the highest resulting score; if it's the minimizing player's turn, pick the move with the lowest resulting score.
  5. Return this best score up through the recursion — the very top-level call reveals the best move to make right now.

Tic-Tac-Toe Solver Worked Example

Input: a nearly-full 3x3 board with one empty cell left

With only one empty cell remaining, minimax simply evaluates the single resulting board: if placing the mark there completes three-in-a-row for the maximizer, the score is +1 (a win); if it completes a row for the opponent (already impossible in this state) it would be -1; otherwise, if the board becomes full without a winner, the score is 0 (a draw). This score is returned as the result of the only available move.

Python · Game Theory Algorithms in Code
def evaluate(board):
    # board: 3x3 with 'X', 'O', or ''
    lines = board + [list(col) for col in zip(*board)]
    lines += [[board[0][0], board[1][1], board[2][2]],
              [board[0][2], board[1][1], board[2][0]]]
    for line in lines:
        if line[0] == line[1] == line[2] and line[0]:
            return 10 if line[0] == 'X' else -10
    return 0

def best_move(board):
    # minimax for 3x3 — returns (row, col) of best move for X
    def score(board, turn):
        e = evaluate(board)
        if e != 0:
            return e
        if all(cell for row in board for cell in row):
            return 0    # draw
        if turn == 'X':
            best = float('-inf')
            for r in range(3):
                for c in range(3):
                    if not board[r][c]:
                        board[r][c] = 'X'
                        best = max(best, score(board, 'O'))
                        board[r][c] = ''
            return best
        else:
            best = float('inf')
            for r in range(3):
                for c in range(3):
                    if not board[r][c]:
                        board[r][c] = 'O'
                        best = min(best, score(board, 'X'))
                        board[r][c] = ''
            return best

    best_val = float('-inf')
    move = (-1, -1)
    for r in range(3):
        for c in range(3):
            if not board[r][c]:
                board[r][c] = 'X'
                v = score(board, 'O')
                board[r][c] = ''
                if v > best_val:
                    best_val = v
                    move = (r, c)
    return move

Behind the Scenes Execution

Press ▶ Run in the visualizer — the call stack, registers and memory will replay here in sync with the code, line by line.

Tic-Tac-Toe Solver Time & Space Complexity

BestO(1) — near end of game
AverageO(b^d)
WorstO(9!) ≈ O(b^d), where b = branching factor (available moves), d = remaining depth — tiny for tic-tac-toe's small board
SpaceO(d) — recursion depth, at most 9 for tic-tac-toe

When to Use Tic-Tac-Toe Solver

  • The foundational algorithm behind unbeatable tic-tac-toe AI, and the starting point for understanding Minimax before tackling larger games like Chess or Connect Four (which need pruning and heuristics).

Recommended resourcesAffiliate links · may earn us a commission

Recommended for learners

Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books Cloud hosting for side projectsShip the portfolio project that gets you hired — free credits for new accounts.Claim credits

Keep the momentum going

Step through a related structure, pattern or course — the ideas reinforce each other and stick faster.