Minesweeper Solver: Deduction Rules and Mine Probabilities
Data Structure DesignModel answerLast updated
Design a Minesweeper bot that derives certain mines and safe cells from overlapping numbers, estimates mine probabilities when it must guess, and is evaluated by win rate.
You are building an automated Minesweeper player. Its objective is to win as often as possible: open every safe cell without ever opening a mine. The bot cannot see the mines, only the visible board.
Suggested interface (refine it as you clarify requirements):
Move = tuple[str, int, int] # ("reveal" or "flag", row, col)
class MinesweeperBot:
def __init__(self, rows: int, cols: int, total_mines: int | None): ...
def next_move(self, board: list[list[str]]) -> Move: ...
The game calls next_move with the current board, applies the move, and repeats until the game is won or lost.
Rules and notation
- The board is a rectangular grid. Each hidden cell may contain a mine.
- Opening a mine loses. Opening every non-mine cell wins.
- An opened safe cell shows the number of mines among its up to eight neighbors (horizontal, vertical, diagonal).
- A flag is your own marker for a suspected mine and reveals nothing.
#= hidden,F= flagged,0-8= opened number.
State any assumptions you need, such as whether the bot knows the total mine count, whether the first click is safe, whether zeros open their neighbors automatically, how mines are distributed, and the board size and time budget per move.
Part 1: Certain moves. Describe and implement rules that find every hidden cell that is certainly a mine or certainly safe. Apply them to this 3x5 board, where row 2 came from opening a zero:
c0 c1 c2 c3 c4
row 0 # # # # #
row 1 1 1 2 1 1
row 2 0 0 0 0 0
Which cells of row 0 can be flagged and which can be opened with no risk?
Part 2: Guessing. When nothing is certain, explain how you estimate the mine probability of every hidden cell (including cells not adjacent to any number) and which cell you open. Cover how overlapping numbers are handled together, how the total mine count and distant cells enter the estimate, how ties are broken, and how you keep the computation tractable.
Part 3: The whole bot. Describe the first move, the order of decisions each turn, the running time of one turn, and how you would demonstrate that your bot beats a simpler one.
Hints
Hint 1
Turn every opened number into an equation: the set of hidden neighbors must contain exactly (number minus adjacent flags) mines. Think of the hidden cells as 0/1 variables.
Hint 2
Besides the single-number rules (all hidden neighbors are mines, or none are), compare two constraints where one hidden set is a subset of the other: the difference of their counts tells you about the leftover cells.
Hint 3
For probabilities, split the frontier into independent components, enumerate valid assignments by backtracking, and weight each assignment by the number of ways to place the remaining mines among the non-frontier cells.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Assumptions to state
- The bot knows the mine count when available (
total_mines), mines are placed uniformly at random, and the first click is safe. Zeros are opened automatically by the game. - Success is judged by win rate over many games. A move may take at most a few hundred milliseconds on typical boards (for example 16x30 with 99 mines).
Part 1: Certain moves
Model. For each opened number cell, let H be its hidden (unflagged) neighbors and k = number - adjacent flags. This gives the constraint "exactly k mines in H". Each hidden cell is a 0/1 variable.
Rules, applied repeatedly until nothing changes:
- If
k == 0, every cell inHis safe. - If
k == |H|, every cell inHis a mine. - Subset rule: if constraints
(A, a)and(B, b)haveA ⊂ B, thenB \ Aholds exactlyb - amines. Ifb - a == 0, all ofB \ Ais safe. Ifb - a == |B \ A|, all of it is mines. - After each discovery, substitute it into all constraints (remove the cell, decrease
kfor mines) and rerun.
Rules 1-3 are sound but not complete for every possible deduction. The probability engine in Part 2 is complete: any cell with probability exactly 0 or 1 is also certain.
Example board. Name the row-0 cells a, b, c, d, e (columns 0-4). The row-1 numbers give:
a + b = 1a + b + c = 1b + c + d = 2c + d + e = 1d + e = 1
Subtracting the first from the second gives c = 0, so (0,2) is safe. Then b + d = 2, so b = d = 1, which forces a = 0 and e = 0.
Result: flag (0,1) and (0,3); reveal (0,0), (0,2), (0,4). This is consistent with all five equations, and the solution is unique.
def neighbors(r, c, R, C):
for dr in (-1, 0, 1):
for dc in (-1, 0, 1):
if (dr or dc) and 0 <= r+dr < R and 0 <= c+dc < C:
yield r+dr, c+dc
def constraints(board):
R, C = len(board), len(board[0])
out = []
for r in range(R):
for c in range(C):
if board[r][c].isdigit():
hidden, flags = set(), 0
for nr, nc in neighbors(r, c, R, C):
if board[nr][nc] == '#': hidden.add((nr, nc))
elif board[nr][nc] == 'F': flags += 1
if hidden:
out.append((frozenset(hidden), int(board[r][c]) - flags))
return out
def deduce(cons):
mines, safe = set(), set()
changed = True
while changed:
changed = False
reduced = set()
for cells, k in cons:
k -= len(cells & mines)
cells = cells - mines - safe
if cells:
reduced.add((cells, k))
cons = list(reduced)
for cells, k in cons:
if k == 0 and not cells <= safe:
safe |= cells; changed = True
elif k == len(cells) and not cells <= mines:
mines |= cells; changed = True
for A, a in cons:
for B, b in cons:
if A < B:
diff, d = B - A, b - a
if d == 0 and not diff <= safe:
safe |= diff; changed = True
elif d == len(diff) and not diff <= mines:
mines |= diff; changed = True
return mines, safe
Note that the pairwise subset check is quadratic in the number of constraints, so index constraints by shared cells in a production version.
Part 2: Choosing when nothing is certain
Why not per-number estimates. Taking k/|H| from one number at a time ignores overlaps and gives wrong risks. The correct quantity is the probability over all full mine layouts consistent with the board.
Exact computation.
- The frontier is the set of hidden cells that touch at least one number. All other hidden cells are the interior.
- Split the frontier into connected components (cells linked by a shared constraint). Components are independent apart from the global mine count.
- For each component, backtrack over assignments, checking constraints as soon as every cell in them is assigned. Record, per mine count
m, the number of valid assignmentsN[m]and, per cell, how many of them place a mine there. - Let
Mbe the mines left (total minus flags) andIthe number of interior cells. A combination of component assignments usingmfrontier mines in total has weightC(I, M - m), because the remaining mines are spread uniformly over the interior. Combine components by convolving overm. - Frontier cell probability = weighted fraction of layouts with a mine there. Interior cell probability =
(M - E[m]) / I, whereE[m]is the expected frontier mine count under the same weights.
If the mine count is unknown, drop the binomial weights (all layouts equally likely per component) and use the board's mine density as the interior estimate.
Choosing the cell. Reveal the minimum-probability cell. Tie-breaks, in order:
- Prefer a cell more likely to be a zero or to yield information, such as one with many hidden neighbors that would resolve frontier constraints.
- Prefer cells adjacent to the frontier, since they tend to unlock deductions.
- Fall back to corners or a fixed order for determinism.
A frontier cell is sometimes riskier than an interior cell, and the bot should pick the interior one in that case.
Keeping it tractable.
- Components keep the search small, since cost is exponential only in component size.
- Order variables along the boundary so constraints close early (strong pruning).
- Cache component results and recompute only components touched by the last move.
- Set a node budget. If exceeded, fall back to a local estimate (average of
k/|H|over adjacent numbers) or a sampled estimate from random consistent layouts. - Use big integers or log-space for the binomial weights on large boards.
Part 3: The complete bot
First move. If the first click is guaranteed safe, open a corner or the center (corners give a higher chance of a zero opening; the center opens more area when it works). Otherwise treat it as a guess with probability M / (R*C).
Per-turn order.
- Keep a queue of already-known certain moves and return those first.
- Run the cheap deduction rules (Part 1). If they find anything, queue it.
- Run the exact component enumeration. Any probability 0 or 1 gives more certain moves.
- Otherwise guess the lowest-probability cell.
- If only interior cells remain unopened and the count of hidden cells equals the mines left, flag them all.
Flagging is optional for winning, since only revealing counts. It helps the bot's own bookkeeping, so flags should only ever be placed for certain mines.
Running time. Let n be the frontier size. Rule-based deduction is roughly linear to quadratic in the number of constraints. Enumeration is worst-case exponential in the largest component, but with pruning and boundary ordering it is typically milliseconds; components larger than about 40 cells are rare and handled by the fallback. Incremental updates make most turns touch only a few components.
Evaluation.
- Simulate thousands of seeded games per configuration (beginner 9x9/10, intermediate 16x16/40, expert 16x30/99). Use the same seeds for every bot.
- Baselines: random reveal, single-point rules only with random guesses, rules plus local probability. Report win rate with a confidence interval (a binomial standard error of about
sqrt(p(1-p)/n)) and compare paired by seed. - Analyze losses: at which guess number did the bot die, what was the probability of the chosen cell, and was a safer cell available? This separates unavoidable risk from bugs.
- Unit tests: the 3x5 example, known forced patterns (1-2-1, 1-1), and a check that the exact probabilities match brute force on small boards.
Common mistakes
- Treating each number independently and ignoring overlaps.
- Ignoring interior cells and the total mine count, so the bot guesses a frontier cell with 40% risk when an interior cell has 20%.
- Not substituting flags into
k, so constraints go stale. - Flagging on a guess rather than on proof, which corrupts later deductions.
- Enumerating the whole frontier as one block instead of by component.