Dynamic Programming21 sections · 916 units
Open in Course

Nim Game - Problem Statement

The classic game

nn stones in a pile. Each turn, remove 1, 2, or 3 stones. Whoever takes the last stone wins. dp[i]dp[i] = true if the player facing ii stones can win. Base: dp[0]=falsedp[0] = false (no stones = you lose). Transition: dp[i]=¬dp[i1]¬dp[i2]¬dp[i3]dp[i] = \lnot dp[i-1] \lor \lnot dp[i-2] \lor \lnot dp[i-3].

If any move leads to opponent losing, you win. Pattern emerges: dp[i]=(imod40)dp[i] = (i \mod 4 \neq 0). Multiples of 4 are losing positions. This is the classic Nim result.