Minesweeper
Algorithm
Game Development
Random Grid Generation
Puzzle Games

What's the algorithm behind minesweeper generation

Master System Design with Codemia

Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.

Introduction

A basic Minesweeper board is generated by placing mines randomly and then computing clue numbers for every non-mine cell. A better Minesweeper board also respects gameplay rules such as a safe first click, optional empty opening around the first move, and sometimes an additional solvability check.

The Basic Board Generation Algorithm

At its core, Minesweeper generation has three steps:

  1. Choose the board size and number of mines.
  2. Place mines into distinct cells.
  3. Compute each non-mine cell’s adjacent mine count.

A minimal Python implementation looks like this:

python
1import random
2
3
4def generate_board(rows, cols, mine_count):
5    board = [[0 for _ in range(cols)] for _ in range(rows)]
6
7    positions = random.sample(range(rows * cols), mine_count)
8    for pos in positions:
9        r = pos // cols
10        c = pos % cols
11        board[r][c] = -1
12
13    directions = [
14        (-1, -1), (-1, 0), (-1, 1),
15        (0, -1),           (0, 1),
16        (1, -1),  (1, 0),  (1, 1),
17    ]
18
19    for r in range(rows):
20        for c in range(cols):
21            if board[r][c] == -1:
22                continue
23            count = 0
24            for dr, dc in directions:
25                nr, nc = r + dr, c + dc
26                if 0 <= nr < rows and 0 <= nc < cols and board[nr][nc] == -1:
27                    count += 1
28            board[r][c] = count
29
30    return board

Here -1 represents a mine, and every other cell stores the number of adjacent mines.

Safe First Click

Most modern Minesweeper implementations do not finalize mine placement until the player makes the first move. That way, the first clicked cell is guaranteed not to be a mine.

A common pattern is:

  • wait for the first click
  • exclude that cell from eligible mine positions
  • randomly place mines everywhere else
  • compute clue numbers

If you also want the first click to open into a blank region, exclude the clicked cell and its neighbors from mine placement.

python
1def valid_positions(rows, cols, safe_row, safe_col):
2    excluded = {
3        (safe_row + dr, safe_col + dc)
4        for dr in (-1, 0, 1)
5        for dc in (-1, 0, 1)
6        if 0 <= safe_row + dr < rows and 0 <= safe_col + dc < cols
7    }
8
9    return [
10        (r, c)
11        for r in range(rows)
12        for c in range(cols)
13        if (r, c) not in excluded
14    ]

That simple rule greatly improves playability.

Revealing Empty Areas

Minesweeper gameplay also relies on flood-fill behavior. When the player clicks a cell with zero adjacent mines, the game automatically reveals neighboring empty cells and their bordering numbered cells.

That is usually implemented with DFS or BFS:

python
1from collections import deque
2
3def reveal(board, start_row, start_col):
4    rows, cols = len(board), len(board[0])
5    revealed = set()
6    queue = deque([(start_row, start_col)])
7
8    while queue:
9        r, c = queue.popleft()
10        if (r, c) in revealed:
11            continue
12        revealed.add((r, c))
13
14        if board[r][c] != 0:
15            continue
16
17        for dr in (-1, 0, 1):
18            for dc in (-1, 0, 1):
19                nr, nc = r + dr, c + dc
20                if 0 <= nr < rows and 0 <= nc < cols:
21                    queue.append((nr, nc))
22
23    return revealed

This is not part of mine placement itself, but it is part of the algorithmic behavior players expect from the game.

Solvability Is a Harder Problem

Random placement does not guarantee a board that can be solved without guessing. If you want every board to be logically solvable, generation becomes more complex.

A solvable-board generator usually does this:

  1. generate a candidate board
  2. run a solver against it
  3. accept or reject the board

That turns generation into a search problem rather than a single random placement step.

For many casual implementations, safe first click is enough. For polished puzzle design, solver-based validation is the next level.

Common Pitfalls

The most common mistake is placing mines before the first click and allowing the first move to lose the game. Most players consider that bad design.

Another issue is placing mines with repeated random attempts instead of sampling distinct positions directly. Sampling unique positions is cleaner and avoids accidental duplicates.

People also forget to recompute clue numbers correctly after moving mines to preserve a safe opening.

Finally, do not assume random boards are always fair. Random placement creates playable boards, but not necessarily boards that are solvable without guessing.

Summary

  • Basic Minesweeper generation is random mine placement plus adjacent-count calculation.
  • Better generators delay mine placement until after the first click.
  • Safe-opening rules often exclude the clicked cell and nearby neighbors from mine placement.
  • Flood-fill reveal logic is separate from generation but essential to gameplay.
  • Guaranteed solvability requires extra solver-based validation beyond simple random generation.

Course illustration
Course illustration

All Rights Reserved.