Below is one example of how you might “solve” the Minesweeper probability‐problem. In our example the “state” of the board is given as a 2D Python list where
- a revealed cell is a number 0–8 (the number of mines in its eight neighbors),
- an unrevealed cell is given by –1.
The basic idea is to “focus on the border”: that is, to look at the unrevealed cells that border (are neighbors to) at least one revealed number. (Cells that are “in the middle” of an unrevealed region have no local constraints, and—if you aren’t told how many mines are hidden in total—you would assign them a “global” probability.) For the border we know the constraints exactly: each revealed number tells us how many mines occur among its (unknown) neighbors. One may then “enumerate” all the 0–1 assignments (mine or not) to the border cells that satisfy all of the local constraints, and then compute for every border cell in how many assignments it came out as a mine; the ratio is its probability.
Below is one complete Python example. (Be advised that if many border cells exist the number of assignments grows exponentially so this “brute‐force” method is practical only in a limited region of the board.)
from itertools import product
def get_neighbors(r, c, rows, cols):
"""Return the (row, col) neighbors for a cell at (r,c)."""
neighbors = []
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:
neighbors.append((nr, nc))
return neighbors
def compute_border_probabilities(board):
"""
Given a Minesweeper board (list of lists)
with revealed numbers 0..8 and unrevealed cells = -1,
compute the probability (between 0 and 1) for each unrevealed cell
that is adjacent to at least one revealed cell (the "border")
to contain a mine.
Returns a dict mapping (row, col) -> probability.
NOTE: This code enumerates all assignments on the border.
(In boards with many border cells the number of assignments is exponential.)
"""
rows = len(board)
cols = len(board[0]) if rows > 0 else 0
# Find border cells: unrevealed cells (-1) that are adjacent to at least one revealed cell.
border = set()
for r in range(rows):
for c in range(cols):
if board[r][c] == -1:
# Check if any neighbor is revealed (number ≥ 0)
for nr, nc in get_neighbors(r, c, rows, cols):
if board[nr][nc] != -1:
border.add((r, c))
break
border = list(border)
# Create local constraints.
# For every revealed cell, we have an equation:
# (number of mines among its unknown (i.e. unrevealed) neighbors) == board[r][c].
#
# We only “care” about the ones that involve border cells.
# (For a revealed cell that touches some unrevealed cell that is not on the border,
# you might want to assign that cell a global probability later.)
constraints = []
for r in range(rows):
for c in range(cols):
if board[r][c] >= 0: # revealed cell with a number
nbr_border = [] # neighbors that are in our border set
# (We also count how many unrevealed neighbors are NOT part of the border.)
non_border_unknown = 0
for nr, nc in get_neighbors(r, c, rows, cols):
if board[nr][nc] == -1:
if (nr, nc) in border:
nbr_border.append((nr, nc))
else:
non_border_unknown += 1
# If there are unknown neighbors not in the border then we have an extra degree of freedom.
# For simplicity here we simply use the constraint only if all unrevealed neighbors
# are in the border (i.e. non_border_unknown == 0).
if non_border_unknown == 0 and nbr_border:
# The constraint: sum(mine indicators on nbr_border) == board[r][c]
constraints.append({
'revealed_cell': (r, c),
'neighbors': nbr_border,
'mine_count': board[r][c]
})
# If no constraints exist, we cannot improve on a “global” probability.
if not constraints:
# Return None or an empty probability mapping.
return {pos: None for pos in border}
# We'll enumerate all assignments to the border cells.
# For each of the border cells, we assign either 0 (no mine) or 1 (mine).
total_configurations = 0
mine_occurrences = {pos: 0 for pos in border}
# For bookkeeping, create an index map so we can refer to a border cell by index.
border_index = {pos: idx for idx, pos in enumerate(border)}
n_border = len(border)
# The total number of assignments is 2^(number of border cells), but we'll consider
# only those that satisfy our constraints.
for assignment in product([0, 1], repeat=n_border):
assignment_dict = { border[i]: assignment[i] for i in range(n_border) }
valid = True
# Check each constraint.
for cons in constraints:
total = sum( assignment_dict[pos] for pos in cons['neighbors'] )
if total != cons['mine_count']:
valid = False
break
if valid:
total_configurations += 1
# Count mines in each border cell.
for pos in border:
if assignment_dict[pos] == 1:
mine_occurrences[pos] += 1
# Compute probability for each border cell.
probabilities = {}
if total_configurations == 0:
# No configuration fits the constraints (this might indicate a bug or an inconsistent board)
for pos in border:
probabilities[pos] = None
else:
for pos in border:
probabilities[pos] = mine_occurrences[pos] / total_configurations
return probabilities
# Example usage:
if __name__ == '__main__':
# Here is an example board:
# 1 1 1
# 1 -1 1
# 1 1 1
#
# In this tiny board, the center is unrevealed and every revealed cell says "1" so
# the only possibility is that the unrevealed center cell is a mine.
board = [
[1, 1, 1],
[1, -1, 1],
[1, 1, 1]
]
probs = compute_border_probabilities(board)
for pos, p in sorted(probs.items()):
print(f"Cell {pos} has mine probability: {p:.3f}")
Explanation
-
Neighbors helper:
The function get_neighbors(r, c, rows, cols) returns the valid adjacent coordinates for a given cell.
-
Border Cells:
We scan the board for unrevealed cells (cells equal to –1) that touch at least one revealed (numeric) cell. These “border” cells are where the local constraints matter.
-
Constraints:
For every revealed cell we build a constraint. In a perfect model you would have to deal with unrevealed neighbors not on the border too, but for simplicity we only “enforce” the constraint if all unrevealed neighbors lie in our border set. (For a more advanced solver, you may want to “split” the problem into the border and the interior, assigning a global probability to the interior.)
-
Enumeration:
We enumerate every 0–1 assignment to the border cells and keep only those that satisfy every constraint exactly. For each valid assignment we count how many times each cell was a mine.
-
Result:
Finally, the code computes the probability for each border cell as
(number of times cell was a mine) ÷ (number of valid assignments).
This is just one way to “solve” the problem. (For real‐world “Minesweeper solvers” there are many performance tricks, such as working on independent “regions” of the board and using constraint propagation rather than full enumeration.)