Skip to lesson

Game theory dynamic programming

Game theory dynamic programming analyzes two-player deterministic games with perfect information. We begin with game trees to see how players alternate maximizing and minimizing payoffs.

Brute Force Game Trees and Why They Blow Up

A game tree search decides whether the player to move can force a win. If any legal move leaves the opponent in a losing position, the current player wins. Each turn here takes 1, 2 or 3 stones (shown after the code).

Java
boolean canWin(int stones) {    for (int take = 1; take <= 3; take++) {        if (stones >= take && !canWin(stones - take)) {            return true;  // this move leaves the opponent in a losing position        }    }    return false;         // every move lets the opponent win}

Why is this slow? In games like stone picking or Nim, each turn branches into multiple choices. A game lasting d moves generates a minimax tree of b^d nodes. For d = 30 and b = 3 choices, 3^30 is over 200 trillion game states!

However, different move sequences frequently reach the exact same board state (e.g. remaining piles {2, 3, 4}). Storing winning/losing outcomes for each game state collapses exponential minimax trees into polynomial dynamic programming.

Winning and Losing Position Definitions

In normal play, the last player to move wins (a player with no legal moves loses). The table below labels each pile size for a game where a turn takes 1 or 2 stones (shown after the code).

WinLoseTable.javaJava
public class WinLoseTable {    public static void main(String[] args) {        boolean[] win = new boolean[7]; // win[0] = false: no moves left        StringBuilder row = new StringBuilder("L");        for (int s = 1; s <= 6; s++) {            // W if some move (take 1 or 2) leaves the opponent in L            win[s] = !win[s - 1] || (s >= 2 && !win[s - 2]);            row.append(win[s] ? " W" : " L");        }        System.out.println("stones 0..6: " + row);    }}
Output
stones 0..6: L W W L W W L

Every position is classified as either a winning state (W-state) or losing state (L-state) for the player whose turn it is to move:

  • A position is winning if at least ONE legal move leads to a losing state for the opponent.
  • A position is losing if EVERY legal move leaves the opponent in a winning state.

Terminal states with no available moves are defined as losing positions.

Minimax and Alternating Score Differentials

When games award points instead of simple win/loss outcomes, we compute the maximum net score lead: my_score - opponent_score.

Example 1 · Stone Game by trying every move, brute force: O(2^n) time, O(n) space

StoneGameBruteDemo.javaJava
public class StoneGameBruteDemo {    static int diff(int[] piles, int left, int right) {        if (left == right) return piles[left];        int takeLeft = piles[left] - diff(piles, left + 1, right);        int takeRight = piles[right] - diff(piles, left, right - 1);        return Math.max(takeLeft, takeRight);            // try both ends every time    }
    public static void main(String[] args) {        int[] piles = {5, 3, 4, 5};        System.out.println("Max score difference: " + diff(piles, 0, piles.length - 1));    }}
Output
Max score difference: 1

What this code does

  • diff(left, right) is the best score lead for the player to move on the piles left..right.
  • Taking a pile adds its value, and the opponent's best lead from the smaller range is subtracted.
  • The same ranges appear in many different move orders, so the work doubles with each extra pile.

Example 2 · Stone Game with interval DP, optimal: O(n²) time, O(n²) space

StoneGameDemo.javaJava
public class StoneGameDemo {    public static int maxScoreDiff(int[] piles) {        int n = piles.length;        int[][] dp = new int[n][n];
        // Base case: single pile        for (int i = 0; i < n; i++) dp[i][i] = piles[i];
        // Interval DP by length        for (int len = 2; len <= n; len++) {            for (int i = 0; i <= n - len; i++) {                int j = i + len - 1;                dp[i][j] = Math.max(piles[i] - dp[i + 1][j], piles[j] - dp[i][j - 1]);            }        }        return dp[0][n - 1];    }
    public static void main(String[] args) {        int[] piles = {5, 3, 4, 5};        System.out.println("Max score difference: " + maxScoreDiff(piles));    }}
Output
Max score difference: 1

What this code does

  • Defines dp[i][j] as maximum score difference on subarray [i..j].
  • Player chooses between left pile minus opponent gain or right pile minus opponent gain.
  • Evaluates in O(n^2) time by interval length, yielding a net lead of 1 for Player 1.
  • Why faster: the best score difference for a range [i, j] is stored once, so the 2^n game sequences collapse into n² ranges.

If you take a move with immediate gain g, the opponent faces the resulting state and earns optimal net score dp[nextState]. Because the opponent's points count against you, your net lead is g - dp[nextState]. The recurrence maximizes over all legal moves: dp[state] = Math.max(gain - dp[nextState]). In Stone Game on piles[i..j], taking from ends gives dp[i][j] = Math.max(piles[i] - dp[i + 1][j], piles[j] - dp[i][j - 1]).

The Nim Game and Sprague-Grundy Theorem

In the game of Nim with multiple stone heaps, Charles Bouton proved that a position is winning if and only if the bitwise XOR sum (Nim-sum) of all heap sizes is non-zero.

Example 3 · Nim by searching every move, brute force: exponential time, O(n) space

NimSearchDemo.javaJava
public class NimSearchDemo {    static boolean canWin(int[] piles) {        for (int i = 0; i < piles.length; i++) {            for (int take = 1; take <= piles[i]; take++) {                piles[i] -= take;                boolean opponentWins = canWin(piles);                piles[i] += take;                        // undo the move                if (!opponentWins) return true;          // this move leaves them losing            }        }        return false;                                    // no moves, or every move loses    }
    public static void main(String[] args) {        int[] game1 = {3, 4, 5};        int[] game2 = {1, 2, 3};        System.out.println("Game 1: " + (canWin(game1) ? "Player 1 wins" : "Player 2 wins"));        System.out.println("Game 2: " + (canWin(game2) ? "Player 1 wins" : "Player 2 wins"));    }}
Output
Game 1: Player 1 wins
Game 2: Player 2 wins

What this code does

  • A position is winning if some move leaves the opponent in a losing position.
  • Each move removes 1 or more stones from one pile; the code undoes the move after the recursive call.
  • It gives the same two answers as the XOR rule, but the search grows quickly with bigger piles.

Example 4 · Nim winner with the XOR rule, optimal: O(n) time, O(1) space

NimGameDemo.javaJava
public class NimGameDemo {    public static boolean canWinNim(int[] piles) {        int xorSum = 0;        for (int p : piles) {            xorSum ^= p;        }        return xorSum != 0;    }
    public static void main(String[] args) {        int[] game1 = {3, 4, 5};        int[] game2 = {1, 2, 3};        System.out.println("Game 1: " + (canWinNim(game1) ? "Player 1 wins" : "Player 2 wins"));        System.out.println("Game 2: " + (canWinNim(game2) ? "Player 1 wins" : "Player 2 wins"));    }}
Output
Game 1: Player 1 wins
Game 2: Player 2 wins

What this code does

  • Computes the bitwise XOR sum of all heap sizes in O(n) time.
  • For game 1, 3 ^ 4 ^ 5 = 2 != 0, so Player 1 can force a win.
  • For game 2, 1 ^ 2 ^ 3 = 0, meaning every move leaves a non-zero Nim-sum for Player 2 to win.
  • Why faster: the XOR of the pile sizes decides the winner, so no search is needed: one pass over the piles.

Example 5 · Subtraction game Grundy values: O(n · moves) time, O(n) space

GrundyDemo.javaJava
import java.util.*;
public class GrundyDemo {    public static int[] computeGrundy(int n) {        int[] g = new int[n + 1];        for (int i = 1; i <= n; i++) {            Set<Integer> nextG = new HashSet<>();            if (i >= 1) nextG.add(g[i - 1]);            if (i >= 2) nextG.add(g[i - 2]);            if (i >= 3) nextG.add(g[i - 3]);
            int mex = 0;            while (nextG.contains(mex)) mex++;            g[i] = mex;        }        return g;    }
    public static void main(String[] args) {        int[] g = computeGrundy(7);        System.out.println("Grundy values for 0..7: " + Arrays.toString(g));    }}
Output
Grundy values for 0..7: [0, 1, 2, 3, 0, 1, 2, 3]

What this code does

  • Computes the mex (minimum excludant) of reachable next-state Grundy values.
  • Reveals a clear repeating pattern G(i) = i % 4.
  • Any pile where G(i) != 0 is a winning position for the first player.

The Sprague-Grundy theorem extends this to ALL impartial turn-based games. Every game state maps to an equivalent Nim heap size called its Grundy value: G(state) = mex({G(nextState)}), where mex is the smallest non-negative integer missing from the set. A composite game with multiple independent components is won by player 1 if and only if the XOR sum of the component Grundy values is non-zero.

Next step

Check your understanding

10 quick questions