Build a Minesweeper Engine That Scales to Huge Sparse Grids
Data Structure DesignModel answerLast updated
Design a Minesweeper class with board rendering and click handling via flood fill, then adapt it to enormous boards with few mines using lazy state and on-demand counting.
Build a Minesweeper engine for a grid with m rows and n columns. When a game starts, k mines are placed at random distinct cells.
Your class should offer these operations:
render()returns a readable string of what the player currently sees. Covered cells appear as hidden. Uncovered cells show the number (0 to 8) of mines in their eight surrounding cells. Flag support is optional, but if you add it, keep the interface clear.click(r, c)uncovers a cell:- If the cell holds a mine, the game ends in a loss.
- Otherwise the cell is uncovered. If its neighboring-mine count is 0, uncover the whole connected area of zero-count cells together with the numbered cells bordering it, following the usual Minesweeper rule.
- Handle clicks on cells that are already uncovered, coordinates outside the grid, and clicks made after the game is over. Repeating a click must not change anything.
What to cover in your answer
- The state you store and why.
- The flood-fill algorithm you use and why it is safe on big boards.
- Time and space complexity for each operation.
- A set of test cases, including edge cases.
Follow-up: Suppose m and n are enormous but k is small. How would you make click() fast and keep memory low? Consider ideas such as generating the board lazily, using sparse structures, computing counts only when needed, caching, or limiting work, and discuss the trade-offs of each.
Hints
Hint 1
Separate hidden information (where the mines are) from player-visible information (which cells are uncovered or flagged). Ask whether either truly needs a full m by n array.
Hint 2
Use an iterative queue-based flood fill, and mark a cell as uncovered at the moment you enqueue it so it can never be queued twice. Only expand from cells whose count is 0.
Hint 3
For the huge-board follow-up, sample k distinct indices from range(m*n) instead of building the grid, store mines in a hash set, and compute a cell's count by checking its 8 neighbors on demand. Think about what the first click and a very large empty region do to your cost.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
What a strong answer shows
- A clear split between hidden state (mine locations) and visible state (uncovered cells, flags, game status).
- An iterative flood fill that cannot overflow the call stack.
- Defensive behavior for odd inputs.
- Awareness that a dense
m×nmatrix becomes the bottleneck when the grid is huge and mines are few.
Design
Keep only the data that matters:
mines: a set of(row, col)pairs. Choose them withrandom.sample(range(m*n), k)and convert each indexito(i // n, i % n). This costs O(k) time and memory and never builds the grid.opened: set of uncovered cells.flags: set of flagged cells (optional).status: one of PLAYING, WON, LOST.count_cache: dictionary memoizing neighbor-mine counts.
The neighbor count is never stored for the entire board. It is computed when needed by testing the 8 surrounding positions against mines, which is O(1) per lookup, and then cached.
click(r, c)
- If
(r, c)is outside the grid, raise an error (or return a clear failure) so caller bugs are visible. - If the game is not in PLAYING, or the cell is already opened or flagged, return the current status with no changes. This is what makes repeated clicks idempotent.
- If the cell is a mine, set status to LOST and return.
- Otherwise mark it opened and push it onto a queue. While the queue is non-empty, pop a cell and compute its count. If the count is 0, visit each in-bounds neighbor that is neither opened nor flagged, mark it opened immediately, and enqueue it.
- After the flood, if
len(opened) == m*n - k, set status to WON.
Why this is correct
- A neighbor of a zero-count cell cannot hold a mine, so the flood never uncovers one.
- Expansion passes through zero cells only. Numbered cells get uncovered but are not expanded, which yields exactly the zero region plus its numbered border.
- Marking at enqueue time means each cell enters the queue at most once, so the loop terminates.
- A second click on an uncovered cell returns at step 2, so state is unchanged.
Complexity
| Operation | Time | Space |
|---|---|---|
| Construction | O(k) | O(k) |
click | O(R), R = newly uncovered cells (8 set lookups each) | O(R) for the queue |
render | O(m·n) for a full picture | O(m·n) output |
| Flag toggle | O(1) | O(1) |
Total memory is O(k + opened + flags). Only rendering the whole board costs m·n, and that is inherent to printing it.
Scaling to huge, sparse boards
- Sparse storage. Sets of coordinates replace the dense matrix. Memory follows the number of interesting cells, not the area.
- Lazy counting. Compute a cell's number only when it is reached, then memoize. Untouched regions cost nothing.
- Cheap mine placement.
random.sampleover arangeis O(k) and avoids shuffling m·n items. If k is close to m·n, invert the idea: store the safe cells instead, or switch to a dense bitmap. - Windowed rendering. For giant boards, render only a viewport (a rectangle of rows and columns) rather than the entire grid. Otherwise output size dominates.
- Fully lazy mines. An alternative is to decide mines only when a cell is first inspected, using a deterministic hash of
(seed, r, c)compared against densityk/(m·n). This needs no upfront set but gives only an expected, not exact, mine count. Exactness can be restored by tracking remaining budget, at the price of more complexity. - First-click safety. If the first click must be safe, relocate any mine on that cell (and optionally its neighbors) after the click, which is a small O(1) edit to the set.
Trade-offs
- Memoizing counts speeds repeated lookups but grows with the opened area. Recomputing costs 8 lookups, so for tiny boards skip the cache.
- On a sparse huge board, one click on a zero cell can open a region of size close to m·n. The cost is then unavoidably proportional to R. Mitigations include a cap per click with a resumable frontier (spreading the work across frames), or storing opened space as row intervals or a union-find structure rather than individual cells. These add code complexity.
- Sets use more memory per entry than a bitmap, so on dense or small boards a flat array of bytes wins.
Edge cases and tests
k = 0: first click opens everything and wins.k = m·n: any click loses.- Reject negative
k,k > m·n, and non-positive dimensions. - 1×1 board works with no special handling.
- Clicking an opened cell, a flagged cell, or anything after win/loss changes nothing.
- Flood must not cross flagged cells.
- Out-of-bounds click raises an error.
- Deterministic tests: inject the mine set (or a seed). For example, on a 3×3 board with one mine at
(0,0), clicking(2,2)opens the other 8 cells and wins. With a mine at(1,1), clicking(0,0)shows1and opens only that cell, and clicking the mine afterward gives LOST with later clicks ignored.
Common mistakes
- Recursive DFS that crashes on large open regions.
- Marking cells opened when dequeued, which allows duplicates in the queue and wasted work.
- Expanding from numbered cells, which leaks the flood past the border.
- Allocating a full grid for a sparse board.
- Forgetting win detection or allowing play after the game ends.
import random
from collections import deque
class Minesweeper:
PLAYING, WON, LOST = "PLAYING", "WON", "LOST"
def __init__(self, m, n, k, seed=None, mines=None):
if m <= 0 or n <= 0 or not (0 <= k <= m * n):
raise ValueError("bad parameters")
self.m, self.n = m, n
if mines is None:
rng = random.Random(seed)
mines = {(i // n, i % n) for i in rng.sample(range(m * n), k)}
self.mines = set(mines)
self.k = len(self.mines)
self.opened, self.flags = set(), set()
self.status = self.PLAYING
self.cache = {}
def _ok(self, r, c):
return 0 <= r < self.m and 0 <= c < self.n
def _nbrs(self, r, c):
for dr in (-1, 0, 1):
for dc in (-1, 0, 1):
if (dr or dc) and self._ok(r + dr, c + dc):
yield r + dr, c + dc
def _count(self, r, c):
if (r, c) not in self.cache:
self.cache[(r, c)] = sum(p in self.mines for p in self._nbrs(r, c))
return self.cache[(r, c)]
def click(self, r, c):
if not self._ok(r, c):
raise ValueError("out of bounds")
cell = (r, c)
if self.status != self.PLAYING or cell in self.opened or cell in self.flags:
return self.status
if cell in self.mines:
self.opened.add(cell)
self.status = self.LOST
return self.status
self.opened.add(cell)
q = deque([cell])
while q:
cr, cc = q.popleft()
if self._count(cr, cc) == 0:
for p in self._nbrs(cr, cc):
if p not in self.opened and p not in self.flags:
self.opened.add(p)
q.append(p)
if len(self.opened) == self.m * self.n - self.k:
self.status = self.WON
return self.status
Legend for a renderer: # hidden, F flag, digits 0 to 8 for uncovered cells, * for a mine shown after a loss.