← MAIN
CONSTRAINT COUNTING

MINESWEEPER

Each number counts the mines around it. The agent proves what it can, and guesses only when nothing is certain.
STATUS LOADING PROVEN 0 REVEALED 0 GUESSES 0

HOW TO PLAY

The goal is to reveal every cell that does not hold a mine. A revealed number counts the mines among its eight neighbouring cells.

Click a covered cell to reveal it. The first click is always safe. Right-click, or use FLAG MODE, to flag a cell that is suspected of holding a mine. Flags are notes and do not change the rules.

Press AI STEP to let the agent reveal every cell it can prove safe, or one guess when nothing is certain. AI PLAY repeats those steps until the board is decided.

Game settings
BOARD
SIZE
OVERLAYS
No analysis yet.

HOW IT WORKS

The agent treats each revealed number as a constraint: a statement that a fixed number of mines lie among the covered cells next to it. It makes every move that counting proves safe. When nothing is proven, it guesses the covered cell with the lowest exact chance of being a mine, counted over every layout of mines that fits the numbers and the mine count.

Board, first click and flood fill

Each cell has up to eight neighbours, the cells that touch it sideways, up, down or diagonally. A mine is a cell that holds one. A covered cell that is opened shows its number, the count of mines among its neighbours.12

23
\text{number}(c) = \sum_{n \in N(c)} m_n

Here N(c) is the set of neighbours of cell c, and m_n is 1 when cell n holds a mine and 0 otherwise. A number of 0 means that no neighbour is a mine.

The mines are placed after the first click, not before it. The clicked cell and its neighbours are kept clear, so the first reveal always opens an area. The other mines are placed uniformly at random on the remaining cells.4

4
function PLACE-MINES(first):
    pool ← the cells that are not first and not neighbours of first
    choose the mine cells uniformly at random from pool

The full version is a partial Fisher–Yates shuffle. After k swaps, the first k cells of the pool are a uniform random choice, so each set of mine cells is equally likely. Stopping after mines swaps saves the work of shuffling the rest.

Flood fill. A cell whose number is 0 has no mines around it, so opening it opens all of its neighbours. A neighbour that is also 0 opens its own neighbours in turn. The opening spreads breadth first: cells are opened in the order they were queued, using a first-in, first-out list. A mine ends the game. The game is won when every cell that is not a mine is open.5

5
function REVEAL(cell):
    if cell is covered and not flagged:
        if no mines are placed yet: PLACE-MINES(cell)      # the first click is always safe
        if cell holds a mine: the game is lost
        otherwise:
            open cell with its number
            queue ← [cell]
            while queue is not empty:                     # breadth first
                here ← the first item of queue, removed
                if here shows 0: open each covered, unflagged neighbour of here and queue it

The full version queues each cell when it is opened, and checks value[here] when the cell leaves the queue. A cell is therefore expanded only if it is still zero at that moment. A flagged cell is never opened by a reveal, which is why a flag protects a cell from an accidental click.

Random (baseline)

The random agent chooses one covered cell uniformly at random, with no reasoning. It is the floor that the other agents are measured against.6 On beginner boards it wins 0.0% of 1,000 seeded games (0 wins) and needs 3.36 guesses per game.7

Single-cell rules (level 1)

The agent works at one of three levels. Level 1 uses single cells. Level 2 adds the constraint groups and the mine count. Level 3 adds exact probabilities. The page's AI STEP and AI PLAY run at level 3.8

For a revealed number at cell i, the need is the number of mines still missing around it. A known mine is a covered cell that has been proven to hold a mine, and a known-safe cell is one that has been proven clear. The open neighbours of i are its covered neighbours that are neither.9

9
\text{need}_i = v_i - \bigl|K \cap N(i)\bigr|, \qquad \text{open}_i = \{\, n \in N(i) : n \text{ covered},\ n \notin K,\ n \notin S \,\}

Here v_i is the number shown at i, N(i) is the set of its neighbours, K is the set of known mines, S is the set of known-safe cells, and |\cdot| is the size of a set. If a number needs 0 more mines, its open neighbours are safe. If it needs as many mines as it has open neighbours, they are all mines. Each new fact can change the need of another number, so the rules repeat until nothing changes, which is a fixpoint.10

Example. A 1 with two open neighbours and no known mine needs 1 and has 2 open cells, so neither rule applies. If one of those two is later proven a mine, the need drops to 0, and the other neighbour is proven safe.

11
function RULE-PASS(view):
    repeat until nothing changes:
        for each revealed number v at cell i:
            need ← v − the known mines among its neighbours
            if need = 0:
                mark its open neighbours safe                  # its mines are all placed
            otherwise if need = the number of open neighbours:
                mark its open neighbours as mines              # every open neighbour is a mine

The full version recomputes open and hits for every number on every pass. Each pass that adds a fact sets the flag that drives the next pass, and the loop stops on the first pass that adds nothing. The loop always stops, because each pass that continues adds at least one cell to KNOWN-MINES or KNOWN-SAFE, and there are only so many covered cells.

If no cell is proven, the rules agent guesses uniformly among the covered cells that are not proven mines.12

Constraint groups and exact counts (level 2)

Each revealed number that still has open neighbours gives one constraint: exactly \text{need}_i of its open cells are mines. Write x_n = 1 when covered cell n is a mine and x_n = 0 when it is safe. The constraint is then a linear equation in those values.13

13
\sum_{n \in O_i} x_n = \text{need}_i, \qquad x_n \in \{0, 1\}

Here O_i is the set of open cells of number i. Two constraints that share an open cell are linked, and a set of linked constraints forms a component, a group that has to be solved together. Components with no shared cell are independent. Once the total number of mines is fixed, each component can be counted on its own.14

A component is counted by backtracking, a depth-first search that assigns one cell at a time and abandons a branch as soon as a constraint cannot be met. The cells are visited in row-major order. Each search state is the index of the next cell together with the residual need of every open constraint, the number of mines it still requires. Two partial layouts that reach the same state have the same future, so the count is stored under that state and reused. This is memoization.15

The count is kept by mine total. A[k] is the number of layouts that use exactly k mines. Independent components are combined by convolution, a sum of products over all ways of splitting the total:

16
(A \ast B)[k] = \sum_{a + b = k} A[a]\, B[b]

Here A and B are layout-count tables of two independent components, and (A \ast B)[k] is the number of layouts of both together that use k mines.

15
function COUNT(i, needs):                # cells i onward; needs = mines each open constraint still wants
    if i is past the last cell: return [1]
    if (i, needs) was seen: return its stored counts
    counts ← zeros
    for x in 0 and 1:                     # cell i is safe, or a mine
        if every constraint on cell i still fits x:
            counts ← counts + COUNT(i + 1, updated needs), shifted by x
    store counts for (i, needs)
    return counts

The full version has the same states as the simple one, with the bookkeeping spelled out. A constraint that has not started yet still has its full need. The check r > after prunes a branch early, when the cells left in the constraint cannot supply the mines it still wants. The fixed argument forces one cell to a value, which gives the layouts in which that cell is a mine. The work is charged to the budget in the next section.

Example. Take three cells in row-major order, a, b, c, with the constraints x_a + x_b = 1 and x_b + x_c = 1. If b is a mine, then a and c are safe, giving one mine in total. If b is safe, then a and c are mines, giving two. So the component's table is [0, 1, 1].

Exact mine probability (level 3, default)

A layout is a full assignment of mines to the covered cells that satisfies every constraint and uses the board's mine count. Every layout is treated as equally likely, so a cell's probability is the share of layouts that put a mine on it. The weight of a set of layouts is simply how many there are. All weights are integers, so comparisons are exact, and the one division is done at the end.

The frontier is the set of cells that appear in some constraint. The interior is the rest of the covered cells, which touch no number. Let R be the mines not yet proven, and let t be the number of mines on the frontier. The other R - t mines fall among the interior's cells in \binom{|I|}{R-t} ways. \binom{n}{k} is the binomial coefficient, the number of ways to choose k of n cells. It is 0 when k is negative or larger than n.17

18
W = \sum_{t} G[t]\, \binom{|I|}{R - t}, \qquad G = A_1 \ast A_2 \ast \cdots \ast A_c

Here W is the weight of all layouts, A_1 \ldots A_c are the layout-count tables of the c components, G[t] is the number of ways the frontier can hold t mines, and I is the interior.

For a cell c on the frontier of component K, the weight of the layouts in which c is a mine is built from that component's with-mine counts and from the other components, combined:

19
N_c = \sum_{j} A^{(c)}_K[j]\, R_K[j], \qquad R_K[j] = \sum_{s} B_K[s]\, \binom{|I|}{R - j - s}

Here A^{(c)}_K[j] is the number of layouts of K that have c as a mine and j mines in total. B_K is the convolution of the layout tables of all the other components. R_K[j] is the weight of the full layouts in which K uses j mines.

Interior cells are interchangeable, so each has the same weight. For a fixed count k of interior mines, a given interior cell is a mine in \binom{|I|-1}{k-1} of the \binom{|I|}{k} placements. Summing over the possible values of k, weighted by G[t], gives:

20
N_c = \sum_{t} G[t]\, \binom{|I| - 1}{R - t - 1}

Finally, the probability of a covered cell c is its weight divided by the total weight:

21
p_c = \frac{N_c}{W}

Here N_c is the weight of the layouts in which c is a mine, and W is the weight of all layouts. If N_c = 0, no layout puts a mine on c, so c is proven safe. If N_c = W, every layout does, so c is proven a mine. These are the proofs that AI STEP plays.22

Example. Suppose three interior cells remain and one mine is left among them. Then \binom{3}{1} = 3 layouts exist. Each cell is a mine in \binom{2}{0} = 1 of them, so its probability is 1/3.

2324
function ANALYSE(view):
    prove every cell that the single-cell rules settle
    group the numbers into components that share covered cells
    count the layouts of each component, by mine total
    combine the components, the interior and the mine count
    for each covered cell:
        probability ← the layouts with a mine there ÷ all layouts
    a cell that no layout fills with a mine is safe; one that every layout fills is a mine

The full version is the exact count, step by step. Each component is counted twice: once with no restriction, and once for every frontier cell forced to a mine. The per-component results are cached on the component's cells and constraints, so an unchanged component costs nothing on the next move. The check total = 0 is the only place where contradictory numbers are reported as an error, since the counts are the only thing that can see that no layout fits.

The probability of a frontier cell uses the other components only through their combined table others. Since the components are independent once the total is fixed, the mines that the others take are summed over every split that is possible.

Ties. Ties are common on the interior, where every cell has the same weight. The agent guesses the covered cell with the lowest N_c. The tie-break prefers the cell with the most covered neighbours, because revealing it can open the most covered cells if it is a zero. The final tie-break is the lower cell number. Exact weights are compared as integers, so two cells never tie through rounding.25

25
function BEST-GUESS(analysis):
    return the covered cell with the lowest mine probability
           # ties: most covered neighbours first, then the lower cell number

The full version compares a tuple of three keys. Negating the neighbour count makes a larger count sort first, and the cell number at the end makes the choice deterministic. In estimate mode the same keys are used with the estimated probabilities.

Work budget and estimates

The exact count can grow quickly on a wide frontier with long chains of numbers. Every new memo state and every convolution is charged to a work budget of 2,000,000 units, where a unit is roughly one Python operation. The budget is set by WORK_BUDGET.2627 When it runs out, the analysis keeps the single-cell proofs, which were found before counting, and reports estimated probabilities instead. The reply carries exact: false, and the page says so. An estimate never proves a cell.28

29
\hat{p}_c = \min\Bigl(1,\ \frac{1}{|K_c|} \sum_{k \in K_c} \frac{\text{need}_k}{|O_k|}\Bigr) \quad (c \in \text{frontier}), \qquad \hat{p}_c = \min\bigl(1, \max\bigl(0, \tfrac{R - \sum_{f \in \text{frontier}} \hat{p}_f}{|I|}\bigr)\bigr) \quad (c \in I)

Here K_c is the set of constraints that contain frontier cell c, O_k is the open cells of constraint k, and \hat{p}_c is the estimated mine probability of c. A frontier cell gets the average density, the need over the number of open cells, of the constraints it sits in. The interior cells share the mines that the frontier estimates do not account for, spread evenly.

30
function ESTIMATE(view, KNOWN-MINES, KNOWN-SAFE):
    keep the single-cell proofs
    for each covered cell next to a number:
        estimate ← the average, over its constraints, of need ÷ number of open cells
    share the mines not accounted for evenly among the interior cells

The full version builds the same constraints as the exact count, so both see the same frontier and interior. The min(1, …) keeps each estimate a probability. The estimates shade the heat map and rank guesses, and best_guess uses the same tie-break as the exact count. An estimate never proves a cell.

AI STEP and AI PLAY

AI STEP asks the server for the level-3 analysis of the board as it stands, and then applies it. Each certain mine is marked as proven. Every cell proven safe is revealed, one beat at a time, and its reason is logged. If nothing is proven, the agent reveals its lowest-probability guess. A guess also clears any flag on its cell, as a certain move does.31

31
function AI-STEP():
    a ← the analysis of the board from the server, at level 3
    mark the certain mines in a as proven
    if a has cells proven safe:
        for each proven safe cell c, one beat at a time:
            REVEAL(c)                                      # a flood fill may open more cells
    otherwise if a has a guess g:
        REVEAL(g)                                          # the lowest mine probability on the board

The full version has two guards and a pacing rule. The busy flag stops a second step from starting while one is running. The board number gen stops a reply, or a running round, from acting on a board that has since been replaced. The beat is shorter when there are more cells, so a long round reads as a sequence without taking long. AI PLAY repeats AI STEP until the board is decided, the player presses STOP, or a request fails, and it makes one server request per round.

Constants and tie-breaks

Constant or ruleWhat it setsValue
Board sizesRows, columns and mines of each preset9×9 with 10 mines; 16×16 with 40; 16 rows × 30 columns with 99
WORK_BUDGETUnits of work for one exact count2,000,000
_CACHE_LIMITComponent results kept; the cache is cleared when full4,096
Tie-break 1Lowest weight (exact) or lowest estimateSmallest value
Tie-break 2Covered neighbours, the most that a reveal could openMore neighbours wins
Tie-break 3Cell numberLower number wins
First clickThe clicked cell and its neighbours are never minesRule, no weight
BENCH_SEED_BASESeed of the first benchmark game; game i uses seed + i10,000
GAMESBenchmark games per size1,000; 500; 200
Wilson zMultiplier for the 95% interval on win rates1.96

Each of these values is fixed in the code. Nothing was tuned: the probabilities are exact counts, and the proof rules follow from the rules of the game. The tie-breaks were set by hand.323334

Results

The benchmark plays every agent on the same seeded boards, so the comparison is paired. Win rates are shown with a 95% Wilson interval, which behaves better than the normal interval when the rate is near 0 or 1.357

AgentBeginner (1,000 games)Intermediate (500)Expert (200)
random0.0% (0.0–0.4)0.0% (0.0–0.8)0.0% (0.0–1.9)
rules (level 1)79.8% (77.2–82.2)49.2% (44.8–53.6)1.5% (0.5–4.3)
csp (level 2)96.1% (94.7–97.1)85.4% (82.0–88.2)39.0% (32.5–45.9)
probability (level 3)97.5% (96.3–98.3)87.8% (84.6–90.4)48.5% (41.7–55.4)

On beginner boards the probability agent wins 97.5% of games, 902 of its wins without a guess. On expert boards it guesses more often than the constraint agent (2.88 per game against 2.29), and it also wins more of its games (48.5% against 39.0%).36