Minesweeper Move Selection and Exact Risk Bot
Medium · Software Engineering Fundamentals · Software Engineer · Technical Screen
Problem Statement
Implement an automated Minesweeper decision engine and game simulator in Python. On each turn, the agent inspects the current visible grid and chooses one hidden tile either to reveal or to flag so that its full-game win rate is maximized.
A rows x cols grid board: List[List[str]] uses 0-indexed (row, col) coordinates (Cell = Tuple[int, int]) and three tile notations:
'#'— unrevealed tile whose contents are unknown to the player.'F'— player-placed mine flag (trusted as holding a mine).'0'through'8'— revealed safe tile showing how many mines sit among its up to 8 horizontal, vertical, and diagonal neighbors.
Implement the following functions and class matching starter.py:
-
find_certain(board: List[List[str]]) -> Tuple[Set[Cell], Set[Cell]]- Return
(mines, safe)containing every'#'coordinate guaranteed to be a mine or guaranteed to be safe via local deterministic deduction, treating existing'F'tiles as confirmed mines:- Single-clue rules: For each revealed digit, subtract adjacent
'F'tiles and already-proven mines to get the remaining mine countneedacross its unsettled'#'neighborsunknown. Ifneed == 0, every tile inunknownis safe; ifneed == len(unknown), every tile inunknownis a mine. - Pairwise subset rule: Whenever one clue's unsettled neighbor set
Ais a strict subset of another clue's unsettled neighbor setB, the differenceB - Amust containneed(B) - need(A)mines; apply the same0andlen(B - A)checks toB - A. - Repeat deduction passes until an entire pass settles no additional tiles.
- Single-clue rules: For each revealed digit, subtract adjacent
- Raise
ValueErrorif any revealed digit is contradicted (need < 0orneed > len(unknown)), even whenunknownis empty.
- Return
-
mine_probabilities(board: List[List[str]], total_mines: Optional[int], density: float = DEFAULT_DENSITY) -> Dict[Cell, float]- Return
{cell: probability}giving the exact probability that each'#'tile holds a mine, trusting'F'tiles as mines:- When
total_minesis an integer, weight every complete mine placement oftotal_minesmines consistent with all revealed digits and'F'markers equally (including unconstrained'#'tiles far from numbers). - When
total_mines is None, assume each non-flagged'#'tile independently holds a mine with prior probabilitydensity(DEFAULT_DENSITY = 0.2), conditioned on matching all revealed digits.
- When
- Raise
ValueErroriftotal_mines is Noneanddensitylies outside[0.0, 1.0], or if zero valid mine placements matchboard.
- Return
-
MinesweeperBot(rows: int, cols: int, total_mines: Optional[int])next_move(board: List[List[str]]) -> Movereturns(action, row, col)whereactionis"reveal"or"flag"using strict priority:- If
find_certain(board)yields any safe tiles, return("reveal", r, c)for the smallest(r, c)insafe. - Otherwise, if
find_certain(board)yields any mine tiles, return("flag", r, c)for the smallest(r, c)inmines. - Otherwise, compute
mine_probabilities(board, self.total_mines)and return("reveal", r, c)for a'#'tile minimizing mine risk (treating probabilities within1e-9of the minimum as tied). Break ties by fewest adjacent'#'tiles, then by smallest(r, c).
- If
-
play_game(bot: MinesweeperBot, rows: int, cols: int, num_mines: int, rng: random.Random) -> bool- Start from an all-
'#'rows x colsgrid and repeatedly applybot.next_move(board). - Raise
ValueErrorifactionis not"reveal"or"flag", or if(r, c)is out of bounds or not currently'#'. - Placing
"flag"setsboard[r][c] = "F". - On the first
"reveal"at(r0, c0), placenum_minesmines uniformly without replacement viarng.sampleacross all coordinates except(r0, c0)so the opening reveal never hits a mine. - Revealing a mine returns
False. Revealing a safe tile writes its adjacent mine count'0'–'8', automatically flood-filling neighbors whenever a'0'tile is uncovered. ReturnTrueonce allrows * cols - num_minessafe tiles are revealed.
- Start from an all-
Examples
Example 1
Input:
board = [
["#", "#", "#", "#"],
["1", "2", "2", "1"],
["0", "0", "0", "0"],
]
total_mines = 2
Output:
find_certain(board) -> ({(0, 1), (0, 2)}, {(0, 0), (0, 3)})
MinesweeperBot(3, 4, 2).next_move(board) -> ("reveal", 0, 0)
Walk-through: No single digit in row 1 resolves a tile on its own. However, (1, 0) = '1' constrains {(0, 0), (0, 1)} to 1 mine while (1, 1) = '2' constrains {(0, 0), (0, 1), (0, 2)} to 2 mines; subtracting the strict subset forces (0, 2) to be a mine. Symmetrically, comparing (1, 3) = '1' with (1, 2) = '2' forces (0, 1) to be a mine. On the second pass, both corner '1's have their mine requirement satisfied, proving (0, 0) and (0, 3) safe, and the bot reveals the smallest safe coordinate (0, 0).
Example 2
Input:
board = [
["1", "#", "1"],
["#", "#", "#"],
["#", "#", "#"],
]
Output (when total_mines = 2):
mine_probabilities(board, 2) -> {
(0, 1): 3/7, (1, 1): 3/7,
(1, 0): 1/7, (1, 2): 1/7,
(2, 0): 2/7, (2, 1): 2/7, (2, 2): 2/7,
}
MinesweeperBot(3, 3, 2).next_move(board) -> ("reveal", 1, 0)
Output (when total_mines = 4):
mine_probabilities(board, 4) -> {
(0, 1): 0.2, (1, 1): 0.2,
(1, 0): 0.6, (1, 2): 0.6,
(2, 0): 0.8, (2, 1): 0.8, (2, 2): 0.8,
}
MinesweeperBot(3, 3, 4).next_move(board) -> ("reveal", 0, 1)
Walk-through: Either 1 mine sits in the shared pair {(0, 1), (1, 1)} (2 ways) or 2 mines sit at {(1, 0), (1, 2)} (1 way), leaving the remaining mines among the 3 unconstrained row-2 tiles. With total_mines = 2, the 1-mine frontier layouts get weight C(3, 1) = 3 (6 full layouts) and the 2-mine layout gets C(3, 0) = 1 (1 full layout, 7 total), making (1, 0) and (1, 2) safest (1/7); both touch 4 '#' neighbors, so (1, 0) wins by coordinates. With total_mines = 4, weights flip to C(3, 3) = 1 vs C(3, 2) = 3 (5 total layouts), making (0, 1) and (1, 1) safest (1/5 = 0.2), and (0, 1) wins tie-breaking because it touches 3 '#' neighbors versus 6 for (1, 1).
Example 3
Input:
board = [
["#", "#", "#"],
["#", "3", "1"],
]
total_mines = None, density = 0.2
Output:
find_certain(board) -> ({(0, 0), (1, 0)}, set())
mine_probabilities(board, None, 0.2) -> {(0, 0): 1.0, (1, 0): 1.0, (0, 1): 0.5, (0, 2): 0.5}
MinesweeperBot(2, 3, None).next_move(board) -> ("flag", 0, 0)
Walk-through: (1, 2) = '1' restricts {(0, 1), (0, 2)} to 1 mine, which sits strictly inside (1, 1) = '3' over {(0, 0), (0, 1), (0, 2), (1, 0)}. The leftover pair {(0, 0), (1, 0)} must hold 3 - 1 = 2 mines, proving both are mines while {(0, 1), (0, 2)} stays an unresolvable 50/50 split. Because safe is empty and mines is non-empty, next_move flags (0, 0).
Constraints
1 <= rows, cols <= 30, andboardis rectangular with every entry in{"#", "F", "0", "1", "2", "3", "4", "5", "6", "7", "8"}.- In
play_game,0 <= num_mines < rows * cols. - When
total_mines is None,0.0 <= density <= 1.0(otherwise raiseValueError). - Any board state with zero consistent mine layouts must raise
ValueErrorinmine_probabilities(and infind_certainwhen a local clue is violated).
Step-by-step walkthrough
Clarify the rules and break the bot into testable pieces
Start by pinning down every open rule from the prompt so our code handles both standard play and variations:
- Total mine count: Usually displayed on screen (
total_mines: int), which lets us weight configurations accurately. If hidden (total_mines = None), the bot falls back to an independent per-cell mine density (DEFAULT_DENSITY = 0.2). - First reveal safety: Guaranteed safe—the game places mines after the opening click, avoiding that cell (though it is not guaranteed to be a
0). - Zero-cascade opening: Revealing a
0automatically flood-fills its neighbors. Even if an engine did not auto-expand zeros, our0-mine constraint rule would immediately mark all those neighbors safe anyway. - Uniform mine placement: Every valid mine layout consistent with the visible board is equally likely, which gives "exact probability of a mine" a crisp mathematical meaning.
- Success metric: Win rate measured across thousands of simulated games against a controlled baseline, not a single lucky run.
We decompose the system into four clean, independently testable building blocks:
find_certain(board) -> (certain_mines, certain_safe) [Part 1: logic rules] mine_probabilities(board, total_mines) -> {hidden_cell: exact_P(mine)} [Part 2: risk solver] MinesweeperBot.next_move(board) -> ("reveal" | "flag", row, col) [Part 3: move policy] play_game(bot, rows, cols, mines, rng) -> True if board cleared, else False [Part 3: simulator]- Total mine count: Usually displayed on screen (
Turn each revealed number into an equation over hidden cells
Every revealed digit
n('0'through'8') states a simple conservation law: among its up to 8 surrounding neighbors, exactlynhold mines.- Any neighbor already marked
'F'(or already proved to be a mine in an earlier pass) accounts for1of thosenmines, so we subtract1fromneed. - Any revealed digit neighbor (or cell already proved safe) holds
0mines and drops out. - What remains is a constraint
(unknown_cells, need): among this set of unsettled'#'cells, there are exactlyneedmines.
Visible patch: Equation produced at (1, 1) = '2': F # # neighbors: (0,0)='F', (0,1)='#', (0,2)='#', (1,0)='1', ... 1 2 1 subtract 1 for 'F' at (0,0) => need = 2 - 1 = 1 0 0 0 unknown '#' neighbors => {(0, 1), (0, 2)} Constraint: ({(0, 1), (0, 2)}, 1)One crucial safety check: before ignoring numbers whose
unknownset is empty, verify0 <= need <= len(unknown). Otherwise an impossible board like"F1F#"(a'1'touching two flags, givingneed = -1andunknown = set()) would silently produce zero constraints and fool the probability solver later.# Cell: (row, col) 0-indexed coordinates, e.g. (0, 2) Cell = Tuple[int, int] # Move: ("reveal" or "flag", row, col), e.g. ("reveal", 0, 0) Move = Tuple[str, int, int] # Constraint: (set_of_unknown_neighbor_cells, exact_mines_among_them), e.g. ({(0, 0), (0, 1)}, 1) Constraint = Tuple[Set[Cell], int] def neighbors(rows: int, cols: int, r: int, c: int) -> List[Cell]: """Return the up to eight in-bounds cells touching (r, c).""" result = [] for dr in (-1, 0, 1): for dc in (-1, 0, 1): if dr == 0 and dc == 0: continue nr, nc = r + dr, c + dc if 0 <= nr < rows and 0 <= nc < cols: result.append((nr, nc)) return result def build_constraints(board: List[List[str]], known_mines: Set[Cell], known_safe: Set[Cell]) -> List[Constraint]: rows, cols = len(board), len(board[0]) constraints: List[Constraint] = [] for r in range(rows): for c in range(cols): if not board[r][c].isdigit(): continue need = int(board[r][c]) unknown: Set[Cell] = set() # Inspect all 8 neighbors: subtract known mines and collect unsettled '#' cells for cell in neighbors(rows, cols, r, c): value = board[cell[0]][cell[1]] if value == "F" or cell in known_mines: need -= 1 elif value == "#" and cell not in known_safe: unknown.add(cell) # Check consistency BEFORE skipping empty `unknown` sets so boards like "F1F#" fail loudly if need < 0 or need > len(unknown): raise ValueError(f"the number at ({r}, {c}) cannot be satisfied") if unknown: constraints.append((unknown, need)) return constraints- Any neighbor already marked
Find certain moves: single-number rules and the subset rule
From constraints
(cells, need), three deterministic deduction rules find 100%-certain moves without guessing:- All-safe rule (
need == 0): Zero mines remain amongcells, so every cell incellsis safe. - All-mines rule (
need == len(cells)): Every single cell incellsmust be a mine. - Subset subtraction rule (
small_cells < big_cells): Whenever constraint A's unknown setsmall_cellssits completely inside constraint B's larger unknown setbig_cells, the leftover cellsrest = big_cells - small_cellsmust contain exactlyrest_need = big_need - small_needmines! We can immediately test rules 1 and 2 on(rest, rest_need).
Because settling even one cell shrinks every neighboring constraint, we repeat in a
while changed:loop until a full pass discovers nothing new. Trace this exact loop on Example 1's3 x 4board (naming row 0's hidden cellsa0 .. a3):Board: Initial equations from row 1: c0 c1 c2 c3 (1,0)=1 -> {a0, a1} = 1 r0 a0 a1 a2 a3 (1,1)=2 -> {a0, a1, a2} = 2 r1 1 2 2 1 (1,2)=2 -> {a1, a2, a3} = 2 r2 0 0 0 0 (1,3)=1 -> {a2, a3} = 1 Pass 1 (subset subtraction): {a0, a1} = 1 is a strict subset of {a0, a1, a2} = 2 => difference {a2} holds 2 - 1 = 1 mine => a2 = (0, 2) is a MINE! {a2, a3} = 1 is a strict subset of {a1, a2, a3} = 2 => difference {a1} holds 2 - 1 = 1 mine => a1 = (0, 1) is a MINE! Pass 2 (single-number rule after subtracting mines a1 and a2): (1,0)=1 shrinks to {a0} = 1 - 1 = 0 => a0 = (0, 0) is SAFE! (1,3)=1 shrinks to {a3} = 1 - 1 = 0 => a3 = (0, 3) is SAFE!Every tile in row 0 is settled without guessing: flag
(0, 1)and(0, 2), and reveal(0, 0)and(0, 3).def find_certain(board: List[List[str]]) -> Tuple[Set[Cell], Set[Cell]]: # Accumulate deduced hidden cells across passes so new deductions shrink remaining constraints mines: Set[Cell] = set() safe: Set[Cell] = set() changed = True while changed: changed = False constraints = build_constraints(board, mines, safe) # Phase 1: Single-constraint deductions (cheapest check first) for cells, need in constraints: if need == 0: safe |= cells changed = True elif need == len(cells): mines |= cells changed = True if changed: # Rebuild constraints right away so freshly settled cells simplify everything else continue # Phase 2: Pairwise proper-subset subtraction (small_cells < big_cells) for small_cells, small_need in constraints: for big_cells, big_need in constraints: # `<` on Python sets tests strict subset: every cell of small_cells is in big_cells, and big_cells has more if not small_cells < big_cells: continue rest = big_cells - small_cells rest_need = big_need - small_need if rest_need == 0: safe |= rest changed = True elif rest_need == len(rest): mines |= rest changed = True return mines, safe- All-safe rule (
Why exact probabilities require whole-frontier layouts and outside weights
When
find_certainreturns nothing, the bot must guess. A common beginner mistake is computingneed / len(unknown)from a single nearby number. To see why that fails, split all hidden'#'cells into two groups:- Frontier cells (
F): Hidden cells touching at least one revealed number (governed by constraints). - Outside cells (
U): Hidden cells far from the revealed area touching no numbers at all.
Consider Example 2's
3 x 3board, first withtotal_mines = 2, then withtotal_mines = 4:col 0 col 1 col 2 row 0 1 [s1] 1 <-- 4 "frontier" cells: shared s1=(0,1), s2=(1,1), row 1 [L] [s2] [R] left-only L=(1,0), right-only R=(1,2) row 2 # # # <-- 3 "outside" cells (U = 3)Naive single-number division says each
'1'touches 3 hidden cells, so every frontier cell looks like1/3 ≈ 0.333. Now count actual valid full-board layouts instead! Any valid frontier assignment either:- Case A (
k = 1frontier mine): Places 1 mine ons1ors2(2frontier ways), satisfying both'1's at once! - Case B (
k = 2frontier mines): Leavess1, s2empty and places mines on bothL=(1, 0)andR=(1, 2)(1frontier way).
Crucially, if
Munflagged mines remain overall, a frontier assignment usingkmines leavesM - kmines to be placed among theU = 3outside cells inC(U, M - k)(binomial coefficient: "U choose M - k") equally likely ways:If total_mines = 2 (M = 2): k = 1 weight: C(3, 2 - 1) = C(3, 1) = 3 -> 2 ways * 3 = 6 full layouts k = 2 weight: C(3, 2 - 2) = C(3, 0) = 1 -> 1 way * 1 = 1 full layout (Total = 7) P(shared s1) = (1 * 3) / 7 = 3/7 ≈ 0.429 <-- RISKIEST cell on the board! P(side L, R) = (1 * 1) / 7 = 1/7 ≈ 0.143 <-- SAFEST cell on the board! P(outside) = (6*1 + 1*0) / 7 / 3 = 2/7 ≈ 0.286 If total_mines = 4 (M = 4): k = 1 weight: C(3, 4 - 1) = C(3, 3) = 1 -> 2 ways * 1 = 2 full layouts k = 2 weight: C(3, 4 - 2) = C(3, 2) = 3 -> 1 way * 3 = 3 full layouts (Total = 5) P(shared s1) = (1 * 1) / 5 = 1/5 = 0.200 <-- NOW THE SAFEST cell! P(side L, R) = (1 * 3) / 5 = 3/5 = 0.600 P(outside) = (2*3 + 3*2) / 5 / 3 = 4/5 = 0.800Changing
total_minesfrom2to4completely inverted which cells are safest! Solving overlapping constraints jointly and weighting eachk-mine frontier solution byC(U, M - k)captures both effects automatically.- Frontier cells (
Enumerate valid frontier layouts with pruned backtracking
To count all valid frontier assignments grouped by mine count
k, we use backtracking—a recursive search that assigns0(safe) or1(mine) to one frontier cell at a time and abandons (prunes) any partial branch the instant a constraint becomes impossible:- Upper-bound prune (
mines_placed[j] > need): We already placed more mines around numberjthan its digit allows. - Lower-bound prune (
mines_placed[j] + cells_left[j] < need): Even if every remaining unassigned neighbor of numberjwere a mine, we still could not reachneed.
Sorting
frontierby(row, col)keeps nearby cells adjacent in recursion order so constraints finish and prune within just a few steps.def enumerate_frontier(frontier: List[Cell], constraints: List[Constraint]) -> Tuple[Dict[int, int], Dict[int, Dict[Cell, int]]]: # Map each frontier cell to the indices of constraints that mention it for O(degree) updates cell_constraints: Dict[Cell, List[int]] = {cell: [] for cell in frontier} for idx, (cells, _) in enumerate(constraints): for cell in cells: cell_constraints[cell].append(idx) # Track live state per constraint during recursion: mines placed so far and unassigned cells left mines_placed = [0] * len(constraints) cells_left = [len(cells) for cells, _ in constraints] chosen: List[Cell] = [] count: Dict[int, int] = {} hits: Dict[int, Dict[Cell, int]] = {} def place(i: int) -> None: # Base case: all frontier cells assigned and every touched constraint stayed feasible if i == len(frontier): k = len(chosen) count[k] = count.get(k, 0) + 1 per_cell = hits.setdefault(k, {}) for cell in chosen: per_cell[cell] = per_cell.get(cell, 0) + 1 return cell = frontier[i] for is_mine in (0, 1): # Apply tentative assignment (0 = safe, 1 = mine) to every constraint containing `cell` for j in cell_constraints[cell]: mines_placed[j] += is_mine cells_left[j] -= 1 # Prune immediately if any constraint already has too many mines or cannot reach `need` still_possible = True for j in cell_constraints[cell]: need = constraints[j][1] if mines_placed[j] > need or mines_placed[j] + cells_left[j] < need: still_possible = False break if still_possible: if is_mine: chosen.append(cell) place(i + 1) if is_mine: chosen.pop() # Undo state changes before trying the next branch for j in cell_constraints[cell]: mines_placed[j] -= is_mine cells_left[j] += 1 place(0) return count, hits- Upper-bound prune (
Convert layout counts into exact mine probabilities
Once
enumerate_frontierreturns(count, hits),configuration_weightassigns eachk-mine frontier configuration its exact multiplicity:- Known
total_mines:comb(outside, total_mines - flags - k)(returning0ifrest < 0orrest > outside). Python uses arbitrary-precision integers, so evencomb(400, 90)never overflows. - Unknown
total_mines(None): Each hidden cell is independently a mine with probabilitydensity(d). Ak-mine assignment onFfrontier cells has probabilityd^k * (1 - d)^(F - k). Dividing out the common(1 - d)^Ffactor when0 < d < 1gives relative weight(d / (1 - d)) ** k(with explicit checks ford == 0.0andd == 1.0so we never divide by zero), while unconstrainedoutsidecells simply have probabilityd.
DEFAULT_DENSITY = 0.2 # mine density assumed when total_mines is None def configuration_weight(k: int, frontier_size: int, outside: int, total_mines: Optional[int], flags: int, density: float) -> float: if total_mines is None: # Handle boundary densities 0.0 and 1.0 explicitly to avoid dividing by (1 - density) == 0 if density == 0.0: return 1.0 if k == 0 else 0.0 if density == 1.0: return 1.0 if k == frontier_size else 0.0 return (density / (1.0 - density)) ** k rest = total_mines - flags - k if rest < 0 or rest > outside: return 0 return comb(outside, rest) def mine_probabilities(board: List[List[str]], total_mines: Optional[int], density: float = DEFAULT_DENSITY) -> Dict[Cell, float]: if total_mines is None and not (0.0 <= density <= 1.0): raise ValueError("density must lie between 0.0 and 1.0") rows, cols = len(board), len(board[0]) hidden: List[Cell] = [] flags = 0 for r in range(rows): for c in range(cols): if board[r][c] == "#": hidden.append((r, c)) elif board[r][c] == "F": flags += 1 # Partition hidden cells into `frontier` (adjacent to >= 1 number) and `outside` (unconstrained) constraints = build_constraints(board, set(), set()) frontier_set: Set[Cell] = set() for cells, _ in constraints: frontier_set |= cells # Sorting keeps spatially adjacent cells close together so constraints finish and prune early frontier = sorted(frontier_set) outside = [cell for cell in hidden if cell not in frontier_set] count, hits = enumerate_frontier(frontier, constraints) weight: Dict[int, float] = {} for k in count: weight[k] = configuration_weight(k, len(frontier), len(outside), total_mines, flags, density) # Sum weighted valid layouts across all possible frontier mine counts `k` total_weight = 0.0 for k in count: total_weight += weight[k] * count[k] if total_weight == 0: raise ValueError("no mine layout matches the board") # Frontier cell probability = weighted fraction of valid layouts in which `cell` is a mine probabilities: Dict[Cell, float] = {} for cell in frontier: cell_weight = 0.0 for k in count: cell_weight += weight[k] * hits[k].get(cell, 0) probabilities[cell] = cell_weight / total_weight # Outside cells are symmetric: each carries an equal share of the expected remaining mines if outside: if total_mines is None: outside_probability = density else: expected_outside_mines = 0.0 for k in count: remaining_mines = total_mines - flags - k expected_outside_mines += weight[k] * count[k] * remaining_mines outside_probability = expected_outside_mines / (total_weight * len(outside)) for cell in outside: probabilities[cell] = outside_probability return probabilitiesKeeping exact enumeration fast: Although worst-case backtracking is
O(2^F)forFfrontier cells, constraint pruning keeps real frontiers tiny—across 40 simulated Expert (16 x 30, 99 mines) games, the median frontier reachingmine_probabilitieshad just11cells. For even larger boards, decompose the frontier graph into connected components (disjoint regions sharing no constraints), enumerate each component separately, and combine their mine-count polynomials via a tiny 1D convolution (2 * 2^20work instead of2^40).- Known
Assemble MinesweeperBot, tie-breaking, and the game simulator
Each turn
MinesweeperBot.next_move(board)follows a strict three-tier priority order:- Reveal the smallest certainly safe cell (
min(safe)) fromfind_certain—zero risk and instant new information. - Flag the smallest certain mine (
min(mines))—records the deduction onboardso future calls shrink constraints and frontiers automatically. - Otherwise call
guess(board): Compute exactmine_probabilitiesand reveal the minimum-risk cell (note that if global mine counting proves an outside cell has probability0.0,guesspicks it seamlessly!). Among cells tied within1e-9of the lowest probability, prefer fewest'#'neighbors, then smallest(row, col).
Why break ties toward fewest hidden neighbors? On an empty opening board, every cell ties in mine probability, so the tie-breaker naturally opens the corner
(0, 0)(only 3 neighbors vs 5 on an edge or 8 in the interior). Because the first click is guaranteed safe, fewer neighbors need to avoid mines for the opening cell to reveal a'0'cascade:P(opening click is a '0') Corner (3 nbrs) Edge (5 nbrs) Interior (8 nbrs) Beginner 9x9, 10 mines 0.666 0.503 0.326 Expert 16x30, 99 mines 0.498 0.313 0.154To evaluate scientifically,
play_gameplaces mines lazily after the first click and flood-fills'0's, whileRandomGuessBotshares the exact same(0, 0)opening andfind_certainrules—differing only when forced to guess:Board Bot policy Games Win rate 95% CI Beginner (9x9, 10 mines) MinesweeperBot (exact probabilities) 5,000 91.3% ±0.8% RandomGuessBot (corner open, baseline) 5,000 84.7% ±1.0% Random guess + random first click 5,000 78.4% ±1.1% Intermediate (16x16, 40) MinesweeperBot (exact probabilities) 2,000 77.9% ±1.8% RandomGuessBot (corner open, baseline) 2,000 62.2% ±2.1% Random guess + random first click 2,000 54.9% ±2.2%Isolating the baseline's opening corner proves that exact probability guessing alone adds
+6.6percentage points on Beginner and+15.7points on Intermediate (well outside the1.96 * sqrt(p*(1-p)/n)sampling error), while logging predicted risk vs empirical death rate on every guess audits probability calibration and separates unavoidable 50/50 endgames from informative mid-game trade-offs.- Reveal the smallest certainly safe cell (
Complete solution
from typing import Dict, List, Optional, Set, Tuple from math import comb import random # Cell: (row, col) 0-indexed coordinates, e.g. (0, 2) Cell = Tuple[int, int] # Move: ("reveal" or "flag", row, col), e.g. ("reveal", 0, 0) Move = Tuple[str, int, int] # Constraint: (set_of_unknown_neighbor_cells, exact_mines_among_them), e.g. ({(0, 0), (0, 1)}, 1) Constraint = Tuple[Set[Cell], int] DEFAULT_DENSITY = 0.2 # mine density assumed when total_mines is None def neighbors(rows: int, cols: int, r: int, c: int) -> List[Cell]: """Return the up to eight in-bounds cells touching (r, c).""" result = [] for dr in (-1, 0, 1): for dc in (-1, 0, 1): if dr == 0 and dc == 0: continue nr, nc = r + dr, c + dc if 0 <= nr < rows and 0 <= nc < cols: result.append((nr, nc)) return result def build_constraints(board: List[List[str]], known_mines: Set[Cell], known_safe: Set[Cell]) -> List[Constraint]: """Build one (unknown_cells, remaining_mines) equation per revealed number with unknown neighbors. Flags ('F') and cells in known_mines reduce remaining_mines by 1; cells in known_safe are skipped just like already-revealed numbers. Raises ValueError if any number is contradicted (remaining_mines < 0 or remaining_mines > len(unknown_cells)). """ rows, cols = len(board), len(board[0]) constraints: List[Constraint] = [] for r in range(rows): for c in range(cols): if not board[r][c].isdigit(): continue need = int(board[r][c]) unknown: Set[Cell] = set() # Inspect all 8 neighbors: subtract known mines and collect unsettled '#' cells for cell in neighbors(rows, cols, r, c): value = board[cell[0]][cell[1]] if value == "F" or cell in known_mines: need -= 1 elif value == "#" and cell not in known_safe: unknown.add(cell) # Check consistency BEFORE skipping empty `unknown` sets so boards like "F1F#" fail loudly if need < 0 or need > len(unknown): raise ValueError(f"the number at ({r}, {c}) cannot be satisfied") if unknown: constraints.append((unknown, need)) return constraints def find_certain(board: List[List[str]]) -> Tuple[Set[Cell], Set[Cell]]: """Return (mines, safe): hidden ('#') cells proven to be mines or safe by local deduction. Applies two single-number rules (need == 0 => all safe; need == len(cells) => all mines) plus the pairwise subset rule (if A is a strict subset of B, B - A holds need(B) - need(A) mines) in a fixed-point loop until a full pass settles no new cells. """ # Accumulate deduced hidden cells across passes so new deductions shrink remaining constraints mines: Set[Cell] = set() safe: Set[Cell] = set() changed = True while changed: changed = False constraints = build_constraints(board, mines, safe) # Phase 1: Single-constraint deductions (cheapest check first) for cells, need in constraints: if need == 0: safe |= cells changed = True elif need == len(cells): mines |= cells changed = True if changed: # Rebuild constraints right away so freshly settled cells simplify everything else continue # Phase 2: Pairwise proper-subset subtraction (small_cells < big_cells) for small_cells, small_need in constraints: for big_cells, big_need in constraints: # `<` on Python sets tests strict subset: every cell of small_cells is in big_cells, and big_cells has more if not small_cells < big_cells: continue rest = big_cells - small_cells rest_need = big_need - small_need if rest_need == 0: safe |= rest changed = True elif rest_need == len(rest): mines |= rest changed = True return mines, safe def enumerate_frontier(frontier: List[Cell], constraints: List[Constraint]) -> Tuple[Dict[int, int], Dict[int, Dict[Cell, int]]]: """Backtrack over all valid mine/safe assignments of `frontier` cells. Returns (count, hits): - count[k]: number of valid frontier assignments that place exactly k mines - hits[k][cell]: how many of those k-mine assignments place a mine on `cell` """ # Map each frontier cell to the indices of constraints that mention it for O(degree) updates cell_constraints: Dict[Cell, List[int]] = {cell: [] for cell in frontier} for idx, (cells, _) in enumerate(constraints): for cell in cells: cell_constraints[cell].append(idx) # Track live state per constraint during recursion: mines placed so far and unassigned cells left mines_placed = [0] * len(constraints) cells_left = [len(cells) for cells, _ in constraints] chosen: List[Cell] = [] count: Dict[int, int] = {} hits: Dict[int, Dict[Cell, int]] = {} def place(i: int) -> None: # Base case: all frontier cells assigned and every touched constraint stayed feasible if i == len(frontier): k = len(chosen) count[k] = count.get(k, 0) + 1 per_cell = hits.setdefault(k, {}) for cell in chosen: per_cell[cell] = per_cell.get(cell, 0) + 1 return cell = frontier[i] for is_mine in (0, 1): # Apply tentative assignment (0 = safe, 1 = mine) to every constraint containing `cell` for j in cell_constraints[cell]: mines_placed[j] += is_mine cells_left[j] -= 1 # Prune immediately if any constraint already has too many mines or cannot reach `need` still_possible = True for j in cell_constraints[cell]: need = constraints[j][1] if mines_placed[j] > need or mines_placed[j] + cells_left[j] < need: still_possible = False break if still_possible: if is_mine: chosen.append(cell) place(i + 1) if is_mine: chosen.pop() # Undo state changes before trying the next branch for j in cell_constraints[cell]: mines_placed[j] -= is_mine cells_left[j] += 1 place(0) return count, hits def configuration_weight(k: int, frontier_size: int, outside: int, total_mines: Optional[int], flags: int, density: float) -> float: """Return the relative weight of one valid frontier assignment that uses `k` mines. - Known total_mines: C(outside, total_mines - flags - k) ways to place remaining mines outside. - Unknown total_mines (None): independent Bernoulli(density) prior over hidden cells. """ if total_mines is None: # Handle boundary densities 0.0 and 1.0 explicitly to avoid dividing by (1 - density) == 0 if density == 0.0: return 1.0 if k == 0 else 0.0 if density == 1.0: return 1.0 if k == frontier_size else 0.0 return (density / (1.0 - density)) ** k rest = total_mines - flags - k if rest < 0 or rest > outside: return 0 return comb(outside, rest) def mine_probabilities(board: List[List[str]], total_mines: Optional[int], density: float = DEFAULT_DENSITY) -> Dict[Cell, float]: """Compute the exact probability that each hidden ('#') cell holds a mine. Every complete mine layout consistent with the board is weighted equally when total_mines is given, or by independent probability `density` when total_mines is None. Raises ValueError if no valid mine layout exists. """ if total_mines is None and not (0.0 <= density <= 1.0): raise ValueError("density must lie between 0.0 and 1.0") rows, cols = len(board), len(board[0]) hidden: List[Cell] = [] flags = 0 for r in range(rows): for c in range(cols): if board[r][c] == "#": hidden.append((r, c)) elif board[r][c] == "F": flags += 1 # Partition hidden cells into `frontier` (adjacent to >= 1 number) and `outside` (unconstrained) constraints = build_constraints(board, set(), set()) frontier_set: Set[Cell] = set() for cells, _ in constraints: frontier_set |= cells # Sorting keeps spatially adjacent cells close together so constraints finish and prune early frontier = sorted(frontier_set) outside = [cell for cell in hidden if cell not in frontier_set] count, hits = enumerate_frontier(frontier, constraints) weight: Dict[int, float] = {} for k in count: weight[k] = configuration_weight(k, len(frontier), len(outside), total_mines, flags, density) # Sum weighted valid layouts across all possible frontier mine counts `k` total_weight = 0.0 for k in count: total_weight += weight[k] * count[k] if total_weight == 0: raise ValueError("no mine layout matches the board") # Frontier cell probability = weighted fraction of valid layouts in which `cell` is a mine probabilities: Dict[Cell, float] = {} for cell in frontier: cell_weight = 0.0 for k in count: cell_weight += weight[k] * hits[k].get(cell, 0) probabilities[cell] = cell_weight / total_weight # Outside cells are symmetric: each carries an equal share of the expected remaining mines if outside: if total_mines is None: outside_probability = density else: expected_outside_mines = 0.0 for k in count: remaining_mines = total_mines - flags - k expected_outside_mines += weight[k] * count[k] * remaining_mines outside_probability = expected_outside_mines / (total_weight * len(outside)) for cell in outside: probabilities[cell] = outside_probability return probabilities class MinesweeperBot: """Decision policy: reveal certain safe cell -> flag certain mine -> reveal lowest-risk cell.""" def __init__(self, rows: int, cols: int, total_mines: Optional[int]) -> None: self.rows = rows self.cols = cols self.total_mines = total_mines def next_move(self, board: List[List[str]]) -> Move: mines, safe = find_certain(board) if safe: r, c = min(safe) return ("reveal", r, c) if mines: r, c = min(mines) return ("flag", r, c) return self.guess(board) def guess(self, board: List[List[str]]) -> Move: """Pick the hidden cell with minimum mine risk; break ties by fewest '#' neighbors, then (r, c).""" probabilities = mine_probabilities(board, self.total_mines) lowest = min(probabilities.values()) best: Optional[Cell] = None best_key: Optional[Tuple[int, Cell]] = None for cell in sorted(probabilities): # Treat probabilities within 1e-9 of `lowest` as tied to avoid floating-point rounding noise if probabilities[cell] > lowest + 1e-9: continue key = (self.hidden_neighbors(board, cell), cell) if best_key is None or key < best_key: best, best_key = cell, key assert best is not None return ("reveal", best[0], best[1]) def hidden_neighbors(self, board: List[List[str]], cell: Cell) -> int: """Count how many '#' neighbors touch `cell` (fewer '#' neighbors => higher chance of a 0).""" rows, cols = len(board), len(board[0]) count = 0 for r, c in neighbors(rows, cols, cell[0], cell[1]): if board[r][c] == "#": count += 1 return count class RandomGuessBot(MinesweeperBot): """Evaluation baseline: identical opening corner and certain moves, but uniform random guesses.""" def __init__(self, rows: int, cols: int, total_mines: Optional[int], seed: int = 0) -> None: super().__init__(rows, cols, total_mines) self.rng = random.Random(seed) def guess(self, board: List[List[str]]) -> Move: hidden = [ (r, c) for r in range(self.rows) for c in range(self.cols) if board[r][c] == "#" ] # Match MinesweeperBot's (0, 0) opening so win-rate differences isolate guessing quality if len(hidden) == self.rows * self.cols: return ("reveal", 0, 0) r, c = self.rng.choice(hidden) return ("reveal", r, c) def open_cell(board: List[List[str]], mines: Set[Cell], r: int, c: int) -> int: """Flood-fill reveal starting at (r, c), expanding automatically across 0-cells.""" rows, cols = len(board), len(board[0]) opened = 0 stack = [(r, c)] while stack: cr, cc = stack.pop() if board[cr][cc] != "#": continue around = neighbors(rows, cols, cr, cc) adjacent_mines = sum(1 for cell in around if cell in mines) board[cr][cc] = str(adjacent_mines) opened += 1 if adjacent_mines == 0: for nr, nc in around: if board[nr][nc] == "#": stack.append((nr, nc)) return opened def play_game(bot: MinesweeperBot, rows: int, cols: int, num_mines: int, rng: random.Random) -> bool: """Simulate one full Minesweeper game and return True iff the bot clears every safe cell.""" board = [["#"] * cols for _ in range(rows)] mines: Optional[Set[Cell]] = None revealed = 0 while True: action, r, c = bot.next_move(board) # Validate both action name and explicit bounds so negative indices never wrap around if action not in ("reveal", "flag"): raise ValueError(f"illegal action {action!r}") if not (0 <= r < rows and 0 <= c < cols) or board[r][c] != "#": raise ValueError(f"illegal move {action} on ({r}, {c})") if action == "flag": board[r][c] = "F" continue # Generate mines lazily after the first reveal so the opening click is guaranteed safe if mines is None: candidates = [ (rr, cc) for rr in range(rows) for cc in range(cols) if (rr, cc) != (r, c) ] mines = set(rng.sample(candidates, num_mines)) if (r, c) in mines: return False revealed += open_cell(board, mines, r, c) if revealed == rows * cols - num_mines: return True✅ Submit now — all tests should pass.
Intuition & how it works
Think of every revealed number on a Minesweeper board as a tiny accounting receipt: after subtracting any adjacent flags, it tells you the exact sum of mines hiding in its remaining '#' neighbor tiles. Our bot works in two gears—fast logical deduction when receipts settle tiles with 100% certainty, and exact layout counting when no move is risk-free.
Why does the obvious shortcut—estimating each cell's risk from a single neighbor like remaining_mines / hidden_neighbors—fall short? Adjacent numbers share hidden cells, so their clues interlock globally, and the total mine count on the rest of the board favors frontier solutions that leave a realistic number of mines for the untouched interior. Ignoring either effect produces wrong probabilities and can even trick a bot into clicking the most dangerous cell on the board!
Walk through a tiny concrete trace of both gears:
- Certain deduction (Example 1:
####above1221and0000):(1, 0) = '1'says{(0, 0), (0, 1)}holds1mine, while(1, 1) = '2'says{(0, 0), (0, 1), (0, 2)}holds2mines. Because the first set sits strictly inside the second, subtracting them proves(0, 2)holds2 - 1 = 1mine! Symmetrically(0, 1)is also a mine, and on the next pass both outer'1'clues shrink to0remaining mines, proving(0, 0)and(0, 3)100% safe. - Exact probability counting (Example 2:
1#1 / ### / ###with2total mines): Eitherk = 1mine sits in the shared pair{(0, 1), (1, 1)}(2ways, each leaving1mine for the3unconstrained row-2 outside cells inC(3, 1) = 3ways =6full layouts) ork = 2mines sit at{(1, 0), (1, 2)}(1way, leaving0mines outside inC(3, 0) = 1way =1full layout). Out of6 + 1 = 7equally likely full-board layouts,(1, 0)and(1, 2)contain a mine in just1(P = 1/7), beating both row-2 outside cells (P = 2/7) and the shared pair (P = 3/7), so the bot clicks(1, 0).
Complexity
Let the board have R rows, C columns, H hidden '#' cells, K revealed numbers adjacent to at least one hidden cell, and F frontier cells (hidden cells adjacent to at least one revealed number):
build_constraints—O(R * C)time,O(K)space: We scan allR * Ccells once and inspect at most 8 neighbors per revealed digit, producing at mostK <= R * Cconstraints of size<= 8.find_certain—O(H * (R * C + K^2))worst-case time,O(R * C)space: Each pass runsbuild_constraintsinO(R * C)and, if no single-number rule fired, compares pairs of constraints inO(K^2)(where each set check touches at most 8 cells,O(1)). Because every pass except the last settles at least one of theHhidden cells, at mostH + 1passes can ever run (and in practice usually 2 to 4).mine_probabilities—O(R * C + F * 2^F)worst-case time,O(R * C + F^2)space: Setup scansR * Ccells, then backtracking (recursively trying0or1per frontier cell and undoing on return) explores valid assignments of theFfrontier cells. Although2^Fis the theoretical ceiling, constraint pruning cuts real searches dramatically (medianF = 11on Expert boards). Space holds the board scan, recursion stack of depthF, andhits[k][cell]counts across<= F + 1mine counts (O(F^2)entries).- One
next_movecall: Runsfind_certainon every turn (sub-millisecond) and invokesmine_probabilitiesonly when no local deduction exists.
Edge cases
- Completely hidden opening board:
constraintsandfrontierare empty, so every cell is anoutsidecell with equal risk (total_mines / (R * C)ordensity); the tie-breaker picks(0, 0)(3 hidden neighbors, smallest coordinates). - Zero outside cells (
U = 0): The binomial coefficientC(0, rest)(number of ways to chooserestcells out of0) equals1only whenrest == 0and0otherwise, automatically filtering to frontier layouts that use the exact remaining mine count. - All remaining mines accounted for on the frontier: Outside cells receive exact probability
0.0even though no number touches them (such as(0, 0)and(1, 0)on##21 / ##F1withtotal_mines = 2), soguessreveals them safely. - Unknown total mine count (
total_mines = None), includingdensity = 0.0or1.0: Boundary densities0.0and1.0are handled explicitly without dividing by1 - density, and out-of-range densities raiseValueError. - Contradictory boards (e.g., wrong flags like
F1F#orflags > total_mines):build_constraintschecks0 <= need <= len(unknown)before skipping emptyunknownsets, andmine_probabilitiesraisesValueErrorwhenevertotal_weight == 0. - Floating-point tie noise: Two mathematically identical probabilities accumulated in different orders can differ by
~1e-16; treating cells within1e-9oflowestas tied keeps tie-breaking deterministic. - Illegal bot coordinates in
play_game: Explicit0 <= r < rowsand0 <= c < colschecks prevent negative Python indices like-1from wrapping around to the opposite edge of the board.
Common mistakes
- Computing risk from a single adjacent number (
need / len(unknown)) or averaging nearby numbers instead of solving overlapping constraints jointly. - Giving every valid frontier assignment equal weight (
1) instead of weighting byC(outside, R - k)—which ignores how many ways the leftover mines can sit in the outside region and flips cell rankings whentotal_mineschanges. - Forgetting unconstrained
outsidecells altogether, even though an outside cell is often safer than every cell on a crowded frontier. - Running deduction rules in a single pass instead of looping until reaching a fixed point (a state where another full pass discovers zero new safe cells or mines).
- Skipping the
need < 0check when a revealed digit has zero'#'neighbors left, letting invalid flag placements pass silently. - Benchmarking win rate on 30–50 games (where the 95% confidence interval is
±12+percentage points) or against a baseline that uses a different opening click, conflating corner-opening gains with probability-solver gains.
Alternative approaches
- General pairwise overlap bound: For any two overlapping constraints
(A, need_A)and(B, need_B)—even when neither is a subset of the other—ifneed_B - need_A == len(B - A), then every cell inB - Amust be a mine and every cell inA - Bmust be safe. Adding this rule settles patterns like1-2on an edge in one step at the sameO(K^2)cost. - SAT / Integer Linear Programming + model counting: Encoding each
'#'cell as a0/1variable and each number as a linear equality lets a SAT solver (a boolean satisfiability engine) test whethercell = 1orcell = 0is satisfiable to find all logically certain cells, while exact#SATmodel counters compute probabilities. - Connected-component decomposition + frontier dynamic programming: Covered in detail in the third follow-up below; yields identical exact probabilities in exponentially less time when frontiers split into separate islands or narrow bands.
Follow-up questions
- Suppose two unrevealed tiles form an isolated 50/50 split that no future clue can resolve. Should the agent guess immediately or wait until endgame, and could knowing the global mine total ever break the symmetry? If the two tiles are genuinely isolated—meaning every neighbor around them is already revealed or flagged—guessing immediately versus waiting until the last turn multiplies full-game survival by the exact same
0.5, so guessing right away is strictly better in timed play because it aborts unwinnable boards early without spending CPU cycles solving the rest of the grid. Always verify first that no unrevealed neighbor could later expose a digit touching only one of the two tiles! In a pure 2-tile 50/50 (a + b = 1),total_minescan never break the symmetry because both placements usek = 1mine and receive the identicalC(U, R - 1)outside weight;total_minesonly separates alternatives that consume different mine counts (such as{b}using 1 mine versus{a, c}using 2 mines whenR = 1mine remains). - How would you balance survival odds against expected information gain when one slightly riskier tile is much more likely to trigger a cascade of deductions? Optimize whole-game win probability rather than single-click survival via a one-step lookahead over the handful of candidates near minimum risk. For each candidate tile
xand each digitd in 0..8thatxcould display if safe, exact layout counting givesP(x is safe and shows d)and lets you runfind_certainon that hypothetical grid to see whetherdunlocks deterministic safe moves or leaves another guess. For example, if Tile A has0.20mine risk (0.80safe) and resolves the region70%of the time (leaving a0.30-risk guess the other30%), its regional win rate is0.80 * (0.70 + 0.30 * 0.70) = 0.728, handily beating Tile B with slightly lower immediate risk (0.19,0.81safe) that always leaves the0.30guess (0.81 * 0.70 = 0.567). Because lookahead runs up to 9 sub-solves per candidate, restrict it to near-tied candidates and confirm the win-rate gain empirically. - On a huge grid where active clues form one long continuous perimeter, how can you bound per-turn latency without sacrificing solver quality? First, partition the frontier graph into connected components (subsets of frontier tiles linked through shared number clues), cache unchanged components across turns, and combine their mine-count polynomials via 1D convolution—reducing
2^(F1 + F2)work to2^F1 + 2^F2. Second, when one component forms a long narrow ribbon (say 80 tiles), sweep along the perimeter using dynamic programming over boundary width / treewidth: at stepi, the DP state only records remaining mine counts for the 3–5 clues simultaneously straddling the sweep cut, merging equivalent prefixes in polynomial time instead of branching2^80times. Finally, guard each move with a wall-clock budget: run fastfind_certainfirst, and if exact DP exceeds the cutoff on a dense tangle, fall back to local constraint relaxation or Monte Carlo layout sampling. - How does your probability model adapt when the global number of mines is hidden from the player? Without
total_mines, replace the combinatorialC(U, R - k)outside weight with an independent Bernoulli prior probabilityd(density) per hidden tile, giving eachk-mine frontier assignment relative weight(d / (1 - d)) ** kand every unconstrainedoutsidetile riskd. Mathematically this equals the infinite-grid limit of the fixed-count model, sinceC(U, m - 1) / C(U, m) = m / (U - m + 1) -> d / (1 - d)asU -> infinitywithm / U -> d. In practice you can initializedfrom standard board presets (0.12Beginner,0.16Intermediate,0.21Expert) or updatedonline from the empirical mine fraction observed in settled regions (Beta-Binomial updating), giving up only endgame count deductions where exhausting all mines proves distant tiles safe.
Follow-up questions
- Suppose two unrevealed tiles form an isolated 50/50 split that no future clue can resolve. Should the agent guess immediately or wait until endgame, and could knowing the global mine total ever break the symmetry?
- How would you balance survival odds against expected information gain when one slightly riskier tile is much more likely to trigger a cascade of deductions?
- On a huge grid where active clues form one long continuous perimeter, how can you bound per-turn latency without sacrificing solver quality?
- How does your probability model adapt when the global number of mines is hidden from the player?
Similar questions
- Smallest-First Topological Ordering
- Dynamic Dynasty Succession Without an Initial Monarch
- DOM Button Click Listener and Event Target
- Catalog Search, Filtering, and Pagination
- Case-Insensitive Ticket Queue Filtering and UI State Debugging
- Library Hold-Queue and Loan Reminder Notification Manager