Sparse Minesweeper Engine and Flood-Fill Optimization
Medium · Coding & Algorithms · Software Engineer · Technical Screen
Problem Statement
Implement a sparse Minesweeper game engine on a 0-indexed m x n grid containing k hidden mines, designed so setup and per-move work avoid pre-allocating dense m x n arrays when k is small relative to m * n.
Provide a Minesweeper class with the following interface:
Minesweeper(m: int, n: int, k: int, seed: Optional[int] = None, bombs: Optional[Iterable[Tuple[int, int]]] = None)- Validate parameters: raise
ValueErrorifm < 1,n < 1,k < 0, ork > m * n. - Store mine coordinates in
self.bombsas asetof(row, col)tuples. WhenbombsisNone, samplekdistinct coordinates uniformly at random (reproducible whenseedis given). Whenbombsis supplied, require exactlykdistinct in-bounds coordinates (0 <= r < m,0 <= c < n), raisingValueErrorotherwise.
- Validate parameters: raise
click(r: int, c: int) -> str- Raise
IndexErrorif(r, c)lies outside0 <= r < mor0 <= c < n. - Return the updated game state:
"playing","won", or"lost". - Idempotency: If the game is already
"won"or"lost", or(r, c)is already revealed or flagged, make no state changes and return the current status. - Mine hit: If
(r, c)is inself.bombs, set status to"lost"and return"lost". - Safe reveal & zero expansion: Reveal
(r, c)with its 8-directional neighbor mine count (0–8, including diagonals). Whenever a newly opened cell has count0, automatically expand across all 8-connected0-cells and reveal their surrounding numbered (1–8) border cells, never opening flagged cells. - Victory: As soon as all
m * n - ksafe cells have been revealed, set status to"won".
- Raise
toggle_flag(r: int, c: int) -> bool- Raise
IndexErrorif(r, c)is out of bounds. - While status is
"playing"and(r, c)is unrevealed, add or remove a flag at(r, c); otherwise leave flags unchanged. ReturnTrueif(r, c)is flagged afterward,Falseotherwise.
- Raise
print_board() -> str- Return
mnewline-separated lines, each containingnsingle-space-separated cell tokens:"#"for hidden unflagged cells,"F"for flagged cells,"0"–"8"for revealed safe cells, and"*"for every mine once status is"lost"("*"overrides"F"on a flagged mine).
- Return
Examples
Example 1
Input:
game = Minesweeper(3, 4, 1, bombs=[(0, 3)])
game.toggle_flag(0, 3) # True
game.toggle_flag(1, 3) # True
s1 = game.click(2, 0)
b1 = game.print_board()
game.toggle_flag(1, 3) # False
s2 = game.click(1, 3)
b2 = game.print_board()
Output:
s1 == "playing"
b1:
0 0 1 F
0 0 1 F
0 0 0 0
s2 == "won"
b2:
0 0 1 F
0 0 1 1
0 0 0 0
Walk-through: With a single mine at (0, 3), clicking (2, 0) (count = 0) floods all eight 0-cells plus unflagged numbered border cells (0, 2) and (1, 2), while skipping (1, 3) because it holds a flag (10 of 11 safe cells revealed -> "playing"). Unflagging and clicking (1, 3) reveals the 11th safe cell ("1"), winning the game.
Example 2
Input:
game = Minesweeper(3, 3, 2, bombs=[(0, 1), (2, 0)])
s1 = game.click(1, 1)
game.toggle_flag(2, 0) # True (mine)
game.toggle_flag(2, 2) # True (safe cell)
s2 = game.click(0, 1) # hits mine
s3 = game.click(0, 2) # post-loss no-op
board = game.print_board()
Output:
s1 == "playing", s2 == "lost", s3 == "lost"
board:
# * #
# 2 #
* # F
Walk-through: (1, 1) touches both mines, so click(1, 1) reveals only "2" without spreading. Clicking (0, 1) loses the game: subsequent clicks do nothing, both mines render as "*" (overriding the flag on (2, 0)), and the flag on safe cell (2, 2) stays "F".
Constraints
1 <= m, nand0 <= k <= m * n(otherwise__init__raisesValueError).- Out-of-bounds
(r, c)(including negative indices) must raiseIndexErrorinclickandtoggle_flag. - Initialization must run in
O(k)expected time andO(k)memory whenk << m * n, and flood fill must be iterative so large open boards never hit Python's recursion limit.
Step-by-step walkthrough
Clarify the rules and exact method contracts
Before writing code, pin down every edge case so the API is predictable and unit-testable:
- Game statuses:
click(r, c)returns"playing","won", or"lost". Victory occurs the instant allm * n - ksafe cells are revealed. - Idempotency: An operation is idempotent when repeating it produces the exact same state and return value as doing it once. Clicking an already-revealed cell, a flagged cell, or any cell after
"won"or"lost"leaves the board untouched and returns the current status. - Boundaries and validation: Clicking outside
0 <= r < mor0 <= c < nraisesIndexError; invalid board dimensions (m < 1,n < 1, orkoutside[0, m * n]) raiseValueError. - Flags:
toggle_flag(r, c)marks or unmarks a hidden cell while"playing"and returns the cell's updated flag state (bool). Flagged cells ignore clicks and are never opened by an automatic zero-region expansion. - Rendering (
print_board): One line per row with space-separated symbols:#hidden,Fflagged,0–8revealed count, and*for every mine once lost (overriding any flag placed on a mine). - Deterministic testing: Accept an optional
seedfor random placement and an optionalbombsiterable to construct exact test boards.
- Game statuses:
Pick sparse data structures instead of dense 2D grids
A beginner's first design usually allocates two
m x n2D arrays (counts[m][n]andrevealed[m][n]). That works for10 x 10, but it paysO(m * n)time and memory before the player even clicks once!Instead, store only the cells where something actually exists:
self.bombs : Set[(r, c)] -> {(0, 3)} (k mine positions) self.revealed : Dict[(r, c), int] -> {(2, 0): 0, (0, 2): 1, ...} (opened safe cells -> count) self.flags : Set[(r, c)] -> {(0, 3), (1, 3)} (player flags) self.status : str -> "playing" | "won" | "lost"Memory starts at
O(k)and grows only withO(k + revealed + flagged). Caching each cell's neighbor mine count insideself.revealedat the moment it opens also meansprint_boardnever recomputes counts.Place k random bombs in O(k) time with flat-index sampling
How do we choose
kdistinct cells uniformly at random without building a list of allm * ncoordinates? Number the grid cells0 .. m * n - 1in row-major order, so flat numberflat_indexmaps cleanly torow = flat_index // nandcol = flat_index % n:2 x 3 board (m = 2, n = 3): flat indices: (row, col) = (index // 3, index % 3): 0 1 2 (0,0) (0,1) (0,2) 3 4 5 (1,0) (1,1) (1,2)Python's
rng.sample(range(m * n), k)samples directly from the lazyrangeobject: whenkis much smaller thanm * n, it tracks chosen indices in a small temporary set rather than copying allm * nintegers, keeping setupO(k)expected time and memory!def __init__(self, m: int, n: int, k: int, seed: Optional[int] = None, bombs: Optional[Iterable[Cell]] = None): if m < 1 or n < 1: raise ValueError("the board needs at least one row and one column") if k < 0 or k > m * n: raise ValueError("k must be between 0 and m * n") self.m = m self.n = n if bombs is None: # self.bombs: set of (row, col) bomb coordinates, e.g. {(1, 3), (3, 0)} self.bombs: Set[Cell] = self._random_bombs(k, seed) else: bomb_list = list(bombs) self.bombs = set(bomb_list) # Reject both wrong counts and duplicate coordinates in `bombs`. if len(bomb_list) != k or len(self.bombs) != k: raise ValueError("bombs must contain exactly k distinct cells") for r, c in self.bombs: if not self._inside(r, c): raise ValueError(f"bomb {(r, c)} is outside the board") # self.revealed: maps each opened safe (row, col) -> its adjacent bomb count (0..8) self.revealed: Dict[Cell, int] = {} # self.flags: set of hidden (row, col) cells currently marked with a flag self.flags: Set[Cell] = set() self.status = "playing" def _random_bombs(self, k: int, seed: Optional[int]) -> Set[Cell]: rng = random.Random(seed) bombs: Set[Cell] = set() # Sampling from range(m * n) takes O(k) memory when k << m * n instead of materializing # all m * n coordinates; flat index i maps to row (i // n) and column (i % n). for flat_index in rng.sample(range(self.m * self.n), k): row = flat_index // self.n col = flat_index % self.n bombs.add((row, col)) return bombsCompute 8-direction neighbors and bomb counts on demand
In Minesweeper, adjacency includes all 8 surrounding cells (horizontal, vertical, and diagonal). Isolating bounds checking inside
_insideand_neighborshandles corners (3 neighbors) and edges (5 neighbors) in one place, and_count(r, c)computes the neighbor mine count on demand with at most 8O(1)hash-set lookups inself.bombs:(-1,-1) (-1, 0) (-1,+1) ( 0,-1) (r, c) ( 0,+1) -> skip (0, 0); keep neighbors inside 0 <= nr < m, 0 <= nc < n (+1,-1) (+1, 0) (+1,+1)def _inside(self, r: int, c: int) -> bool: return 0 <= r < self.m and 0 <= c < self.n def _neighbors(self, r: int, c: int) -> List[Cell]: """Return up to 8 valid surrounding cells (including diagonals).""" cells: List[Cell] = [] for dr in (-1, 0, 1): for dc in (-1, 0, 1): if dr == 0 and dc == 0: continue nr = r + dr nc = c + dc if self._inside(nr, nc): cells.append((nr, nc)) return cells def _count(self, r: int, c: int) -> int: """Count adjacent bombs on demand using at most 8 O(1) set lookups.""" total = 0 for neighbor in self._neighbors(r, c): if neighbor in self.bombs: total += 1 return totalHandle guard clauses and O(1) win detection in click
click(r, c)checks every fast exit condition first: out-of-bounds raisesIndexError; a finished game, revealed cell, or flagged cell returnsself.statusunchanged; a mine setsself.status = "lost".Only an unrevealed, unflagged safe cell reaches
_flood_reveal(r, c). Because mines never enterself.revealedand each safe cell enters at most once,len(self.revealed)is the exact count of opened safe cells — making the win check a singleO(1)comparisonlen(self.revealed) == m * n - len(self.bombs)!def click(self, r: int, c: int) -> str: if not self._inside(r, c): raise IndexError(f"cell {(r, c)} is outside the {self.m}x{self.n} board") # Idempotent no-ops: finished game, already-revealed cell, or flagged cell. if self.status != "playing": return self.status if (r, c) in self.revealed or (r, c) in self.flags: return self.status if (r, c) in self.bombs: self.status = "lost" return self.status self._flood_reveal(r, c) # Every entry in self.revealed is a distinct safe cell, so winning is an O(1) size check. total_safe_cells = self.m * self.n - len(self.bombs) if len(self.revealed) == total_safe_cells: self.status = "won" return self.statusExpand zero regions with breadth-first search (BFS) flood fill
When a clicked cell has
0neighbor mines, every one of its 8 neighbors is guaranteed safe, so Minesweeper automatically opens them too — and any neighbor that is also0continues spreading. This region-growing algorithm is called flood fill, implemented here with breadth-first search (BFS) (exploring outward layer by layer using a first-in, first-outdequequeue).Three implementation details prevent subtle bugs:
- Use an explicit
deque, not recursion: On a1000 x 1000empty board (1,000,000cells), recursive depth-first search overflows Python's1000-frame call stack. - Mark
self.revealedBEFORE appending toqueue: Several0-cells often share the same neighbor; recording it inself.revealedon enqueue guarantees each cell is queued at most once. - Reveal numbered border cells, then stop expanding them: When
self.revealed[(cr, cc)] > 0, the cell is already recorded inself.revealed(so the numbered border shows on the board!), andcontinueskips pushing its neighbors (which might include mines!).
3 x 4 board (Example 1), mine at (0, 3), flags at (0, 3) and (1, 3), click(2, 0): Hidden counts: Start queue: [(2,0)] Wave reaches (0,2)=1 & (1,2)=1 -> > 0, stop! 0 0 1 * revealed: {(2,0): 0} Neighbor (1,3) is in self.flags -> skipped! 0 0 1 1 10 of 11 safe cells opened -> "playing" 0 0 0 0def _flood_reveal(self, r: int, c: int) -> None: """Iterative BFS from safe cell (r, c): 0-cells expand outward; numbered cells stop.""" # Record (r, c) as revealed *before* enqueuing so no cell enters the queue twice. self.revealed[(r, c)] = self._count(r, c) # queue: FIFO deque of revealed (row, col) cells whose neighbors may still need opening queue = deque([(r, c)]) while queue: cr, cc = queue.popleft() # Numbered cells (> 0) belong to the visible border, so they stay revealed but do not spread. if self.revealed[(cr, cc)] > 0: continue # Since (cr, cc) has 0 bomb neighbors, every neighbor is guaranteed bomb-free. for nr, nc in self._neighbors(cr, cc): if (nr, nc) in self.revealed or (nr, nc) in self.flags: continue self.revealed[(nr, nc)] = self._count(nr, nc) queue.append((nr, nc))- Use an explicit
Support flags, board rendering, and trace Example 1
toggle_flagmutatesself.flagsonly while"playing"and only on unrevealed cells.print_boardformats each cell by checking_symbolin strict priority order: mines (*) on a lost game first, then revealed digits (0–8), then flags (F), then#.def toggle_flag(self, r: int, c: int) -> bool: if not self._inside(r, c): raise IndexError(f"cell {(r, c)} is outside the {self.m}x{self.n} board") # Flags can only be placed or removed on hidden cells while the game is still active. if self.status == "playing" and (r, c) not in self.revealed: if (r, c) in self.flags: self.flags.remove((r, c)) else: self.flags.add((r, c)) return (r, c) in self.flags def print_board(self) -> str: lines: List[str] = [] for r in range(self.m): row_symbols: List[str] = [] for c in range(self.n): row_symbols.append(self._symbol(r, c)) lines.append(" ".join(row_symbols)) return "\n".join(lines) def _symbol(self, r: int, c: int) -> str: # Once lost, expose all bombs as "*" (taking priority over any misplaced flag on a bomb). if self.status == "lost" and (r, c) in self.bombs: return "*" if (r, c) in self.revealed: return str(self.revealed[(r, c)]) if (r, c) in self.flags: return "F" return "#"Trace Example 1 (
3 x 4board,12cells,k = 1mine at(0, 3),11safe cells):True counts (B=mine) Flags (0,3),(1,3) After click(2, 0) Unflag & click(1, 3) -> "won" 0 0 1 B # # # F 0 0 1 F 0 0 1 F 0 0 1 1 # # # F 0 0 1 F 0 0 1 1 0 0 0 0 # # # # 0 0 0 0 0 0 0 0 (10 safe revealed) (11 safe revealed == 12 - 1)Optimize for huge, sparse boards via coordinate compression
Now consider the sparse-grid scaling challenge:
m = n = 10^5(10^10cells!) with onlyk = 100mines. Our sparse sets already make setupO(k)and numbered clicksO(1), saving ~10 GB of dense grid RAM. What still breaks? Almost the entire10^5 x 10^5board is one giant0-ocean, so the very first click on a0cell tries to insert~10^10individual(r, c)tuples intoself.revealed(hundreds of gigabytes and minutes of CPU)!The fix is coordinate compression — collapsing long empty stretches of rows and columns into single rectangular blocks so BFS visits blocks instead of individual cells:
- Identify "interesting" rows and columns: Only rows
br - 1, br, br + 1around a mine(br, bc)(plus any flagged rowfr) can ever hold a mine, a number1..8, or a flag. Make each interesting row a 1-row band, and merge every contiguous gap of empty rows between them into a single multi-row band; do the same for columns. Withkmines (andf = 0flags), there are at most3ksingle-row bands andk + 1gap bands -> at most4k + 1bands per axis (<= 401bands fork = 100!). - Uniform blocks: Intersecting row bands with column bands partitions the
10^5 x 10^5board into at most(4k + 1)^2 <= 160,801blocks (or(4k + 1 + 2f)^2withfflags):- Every multi-cell block has height or width
>= 2outside all mine neighborhoods, so every cell inside it has count0. - Every
1 x 1block is a single cell: either a mine, a flag, a numbered cell (1..8), or a0cell where one mine's row crosses a distant mine's column.
- Every multi-cell block has height or width
- BFS over blocks & viewport printing: Run the exact same 8-neighbor BFS on the block grid! Opening any
0block adds its full rectangle area(r_end - r_start + 1) * (c_end - c_start + 1)torevealed_safe_countinO(1), bounding worst-case click time and memory toO((k + f)^2)regardless ofmandn. Replaceprint_board()withprint_window(r0, c0, height, width)using binary search (O(log(k + f))) on the band boundaries.
10 x 10 board with 1 mine at (1, 1): interesting rows: {0, 1, 2}, merged gap band: [3..9] (only 4 row bands instead of 10!) interesting cols: {0, 1, 2}, merged gap band: [3..9] (only 4 col bands -> 16 blocks vs 100 cells) col: 0 1 2 | 3..9 row 0: [1] [1] [1] | [0 x 7] row 1: [1] [*] [1] | [0 x 7] row 2: [1] [1] [1] | [0 x 7] --------+-----------+--------- 3..9 : [7x1 zeros] | [7x7 = 49 zeros opened as 1 block!]- Identify "interesting" rows and columns: Only rows
Complete solution
from typing import Dict, Iterable, List, Optional, Set, Tuple import random from collections import deque Cell = Tuple[int, int] class Minesweeper: """An m x n Minesweeper game backed by sparse sets and dictionaries. - Minesweeper(m, n, k, seed=None, bombs=None): places k bombs uniformly at random (reproducible with `seed`), or at `bombs` when provided (requiring k distinct cells). Raises ValueError for m < 1, n < 1, k outside [0, m * n], duplicates, or out-of-bounds bombs. - click(r, c) -> status: reveals (r, c), expanding connected zero regions and their numbered borders via BFS. Repeated clicks, flagged cells, or finished games are no-ops. Out-of-bounds coordinates raise IndexError. Returns "playing", "won", or "lost". - toggle_flag(r, c) -> bool: toggles a flag on a hidden cell while playing; returns whether (r, c) is flagged afterward. Flood fill never reveals a flagged cell. - print_board() -> str: renders one row per line, space-separated: "#" hidden, "F" flagged, "0"-"8" revealed count, "*" all bombs once lost. """ def __init__(self, m: int, n: int, k: int, seed: Optional[int] = None, bombs: Optional[Iterable[Cell]] = None): if m < 1 or n < 1: raise ValueError("the board needs at least one row and one column") if k < 0 or k > m * n: raise ValueError("k must be between 0 and m * n") self.m = m self.n = n if bombs is None: # self.bombs: set of (row, col) bomb coordinates, e.g. {(1, 3), (3, 0)} self.bombs: Set[Cell] = self._random_bombs(k, seed) else: bomb_list = list(bombs) self.bombs = set(bomb_list) # Reject both wrong counts and duplicate coordinates in `bombs`. if len(bomb_list) != k or len(self.bombs) != k: raise ValueError("bombs must contain exactly k distinct cells") for r, c in self.bombs: if not self._inside(r, c): raise ValueError(f"bomb {(r, c)} is outside the board") # self.revealed: maps each opened safe (row, col) -> its adjacent bomb count (0..8) self.revealed: Dict[Cell, int] = {} # self.flags: set of hidden (row, col) cells currently marked with a flag self.flags: Set[Cell] = set() self.status = "playing" def _random_bombs(self, k: int, seed: Optional[int]) -> Set[Cell]: rng = random.Random(seed) bombs: Set[Cell] = set() # Sampling from range(m * n) takes O(k) memory when k << m * n instead of materializing # all m * n coordinates; flat index i maps to row (i // n) and column (i % n). for flat_index in rng.sample(range(self.m * self.n), k): row = flat_index // self.n col = flat_index % self.n bombs.add((row, col)) return bombs def _inside(self, r: int, c: int) -> bool: return 0 <= r < self.m and 0 <= c < self.n def _neighbors(self, r: int, c: int) -> List[Cell]: """Return up to 8 valid surrounding cells (including diagonals).""" cells: List[Cell] = [] for dr in (-1, 0, 1): for dc in (-1, 0, 1): if dr == 0 and dc == 0: continue nr = r + dr nc = c + dc if self._inside(nr, nc): cells.append((nr, nc)) return cells def _count(self, r: int, c: int) -> int: """Count adjacent bombs on demand using at most 8 O(1) set lookups.""" total = 0 for neighbor in self._neighbors(r, c): if neighbor in self.bombs: total += 1 return total def click(self, r: int, c: int) -> str: if not self._inside(r, c): raise IndexError(f"cell {(r, c)} is outside the {self.m}x{self.n} board") # Idempotent no-ops: finished game, already-revealed cell, or flagged cell. if self.status != "playing": return self.status if (r, c) in self.revealed or (r, c) in self.flags: return self.status if (r, c) in self.bombs: self.status = "lost" return self.status self._flood_reveal(r, c) # Every entry in self.revealed is a distinct safe cell, so winning is an O(1) size check. total_safe_cells = self.m * self.n - len(self.bombs) if len(self.revealed) == total_safe_cells: self.status = "won" return self.status def _flood_reveal(self, r: int, c: int) -> None: """Iterative BFS from safe cell (r, c): 0-cells expand outward; numbered cells stop.""" # Record (r, c) as revealed *before* enqueuing so no cell enters the queue twice. self.revealed[(r, c)] = self._count(r, c) # queue: FIFO deque of revealed (row, col) cells whose neighbors may still need opening queue = deque([(r, c)]) while queue: cr, cc = queue.popleft() # Numbered cells (> 0) belong to the visible border, so they stay revealed but do not spread. if self.revealed[(cr, cc)] > 0: continue # Since (cr, cc) has 0 bomb neighbors, every neighbor is guaranteed bomb-free. for nr, nc in self._neighbors(cr, cc): if (nr, nc) in self.revealed or (nr, nc) in self.flags: continue self.revealed[(nr, nc)] = self._count(nr, nc) queue.append((nr, nc)) def toggle_flag(self, r: int, c: int) -> bool: if not self._inside(r, c): raise IndexError(f"cell {(r, c)} is outside the {self.m}x{self.n} board") # Flags can only be placed or removed on hidden cells while the game is still active. if self.status == "playing" and (r, c) not in self.revealed: if (r, c) in self.flags: self.flags.remove((r, c)) else: self.flags.add((r, c)) return (r, c) in self.flags def print_board(self) -> str: lines: List[str] = [] for r in range(self.m): row_symbols: List[str] = [] for c in range(self.n): row_symbols.append(self._symbol(r, c)) lines.append(" ".join(row_symbols)) return "\n".join(lines) def _symbol(self, r: int, c: int) -> str: # Once lost, expose all bombs as "*" (taking priority over any misplaced flag on a bomb). if self.status == "lost" and (r, c) in self.bombs: return "*" if (r, c) in self.revealed: return str(self.revealed[(r, c)]) if (r, c) in self.flags: return "F" return "#"✅ Submit now — all tests should pass.
Intuition & how it works
Picture clearing fog off a grid-based map: stepping on a tile adjacent to hidden mines reveals only the warning number under your boot, while stepping on a "0" tile (meaning zero mines in all 8 surrounding squares) sets off a chain reaction that clears every connected "0" tile plus the single ring of numbered warning tiles framing that clearing. We store only sparse sets and dictionaries (self.bombs, self.revealed, self.flags) rather than pre-allocating dense m x n matrices, compute neighbor mine counts on demand in O(1) via 8 hash-set lookups, and expand "0" clearings with breadth-first search (BFS) (a wave-by-wave traversal using a first-in, first-out collections.deque queue).
Two naive choices get candidates into trouble quickly. Pre-allocating an m x n integer grid and scanning the whole board after every click to check for victory wastes O(m * n) setup RAM and turns every click into O(m * n) work; writing the "0"-region expansion recursively crashes with RecursionError on a 1000 x 1000 open board (1,000,000 stack frames vs Python's 1000 limit). Marking cells in self.revealed before pushing them onto an iterative deque guarantees every safe cell is visited at most once and turns victory detection into a single O(1) check: len(self.revealed) == m * n - k.
Trace Example 1 (3 x 4 board, k = 1 mine at (0, 3), flags placed on (0, 3) and (1, 3)):
- Calling
click(2, 0)finds_count(2, 0) == 0, recordsrevealed[(2, 0)] = 0, and initializesqueue = [(2, 0)]. - BFS ripples across all eight
0-cells ((2,0)..(2,3),(1,0),(1,1),(0,0),(0,1)) and queues their unflagged numbered border cells(0, 2)(count = 1) and(1, 2)(count = 1), while skipping(1, 3)because(1, 3)is inself.flags. - When
(0, 2)and(1, 2)pop, their count is1 > 0, so they stay revealed on the border without expanding into(0, 3)(10of11safe cells open ->"playing"). - Calling
toggle_flag(1, 3)followed byclick(1, 3)opens(1, 3)(count = 1), bringinglen(revealed)to11 == 12 - 1and immediately returning"won".
Complexity
- Initialization (
__init__):O(k)expected time andO(k)space whenkis much smaller thanm * n(up toO(m * n)whenkapproachesm * n), becauserandom.sample(range(m * n), k)samples indices directly from the lazyrangewithout building anm * nlist. click(r, c):O(1)time for every no-op or losing click (out-of-bounds, finished game, already revealed, flagged, or mine). On a newly opened safe region ofRcells,O(R)time because each revealed cell enters and exitsqueueonce and performs at most 8 neighbor checks plus one 8-lookup_countcall; summed across an entire game, allclickcalls combined take at mostO(m * n)time.toggle_flag(r, c):O(1)average time for hash-set lookup and insertion/removal.print_board():O(m * n)time and output string space to emit one symbol for each of them * ncells.- Space:
O(k + revealed + flagged)total game-state memory (bounded above byO(m * n)), avoiding upfrontO(m * n)grid allocation.
Edge cases
- Corners and edges:
_neighborsfilters through0 <= nr < mand0 <= nc < n, naturally yielding 3 neighbors at corners and 5 along edges. - Zero mines (
k = 0) and all mines (k = m * n): Withk = 0, any first click floods allm * ncells and returns"won"; withk = m * n, any click hits a mine and returns"lost". 1 x 1boards:Minesweeper(1, 1, 0).click(0, 0)returns"won"("0");Minesweeper(1, 1, 1).click(0, 0)returns"lost"("*").- Idempotent clicks: Clicking a revealed
0, a revealed number, a flagged cell, or any cell after"won"/"lost"mutates nothing and returnsself.status. - Flags inside a zero region:
_flood_revealskipscell in self.flags, leaving the flagged cell closed until the player unflags and clicks it. - Negative coordinates (
r = -1): Explicitly rejected by_insidewithIndexError(whereas indexing a Python 2D listgrid[-1][0]would silently read the last row!). - Duplicate or out-of-board custom
bombs: Validated in__init__by comparinglen(bomb_list)andlen(set(bomb_list))againstkand checking_insideon every coordinate.
Common mistakes
- Marking cells revealed on
popleft()instead of beforeappend(): Up to 8 adjacent0-cells can push the same unvisited neighbor intoqueuebefore it pops, causing up to 8x redundant work (and corrupting any manual revealed counter). - Refusing to reveal numbered cells (
count > 0) during flood fill: Standard Minesweeper reveals the 1-cell-thick numbered border framing a0-region; numbered cells must be added toself.revealedand only prevented from expanding further. - Using 4-directional adjacency instead of 8-directional: Minesweeper counts diagonal mines and floods diagonally across
0-cells ((0, 0)connects directly to(1, 1)when both are0). - Writing flood fill with recursion: Hits Python's recursion limit on boards larger than ~32 x 32 (
1024cells). - Scanning all
m * ncells after every click to test for victory: Turns every single numbered click fromO(1)intoO(m * n). - Placing
kmines viafor _ in range(k): bombs.add(...)without resampling collisions: Duplicate random draws leave fewer thankmines on the board, breakingm * n - kwin logic.
Alternative approaches
- Precomputed dense
m x n2D arrays: Faster constant factors (grid[r][c]array indexing beats tuple hashing) and very clean for classic30 x 16boards, at the cost of mandatoryO(m * n)initialization time and RAM. - Iterative depth-first search (explicit
liststack instead ofdeque): Reveals the exact same connected region inO(R)time and space without stack overflow, visiting cells in depth-first order rather than concentric waves. - Coordinate-compressed block graph (for huge sparse boards): Partitions rows and columns around the
kmines (andfflags) into at most4k + 1 + 2fbands per axis so BFS runs inO((k + f)^2)block operations independent ofm * n.
Follow-up questions
- How can you guarantee that the player's opening move is always safe and opens a clearing? Defer
_random_bombsuntil the firstclick(r0, c0)arrives (lazy initialization). Exclude(r0, c0)and its 8 neighbors (up toe <= 9cells) from the candidate pool, samplekmines uniformly from the remainingm * n - ecells (for instance by drawing fromrange(m * n)and resampling any index inside the excluded3 x 3patch whenk << m * n), and then run_flood_reveal(r0, c0). Validate upfront thatk <= m * n - e(falling back to excluding only(r0, c0)whenm * n - 9 < k <= m * n - 1). - How would you add a 'chord' action that opens all unflagged neighbors around an already-revealed number? Add
chord(r, c) -> str: ifself.status != "playing"or(r, c)is not inself.revealedorself.revealed[(r, c)] == 0, returnself.status. Otherwise count how many neighbors of(r, c)belong toself.flags; when that flag count equalsself.revealed[(r, c)], callself.click(nr, nc)on every hidden, unflagged neighbor (halting immediately if one of them hits an unflagged mine due to a misplaced flag and transitions to"lost"). - How would you redesign flood fill and rendering when the grid is 100,000 by 100,000 with only 100 mines? Cell-by-cell
self.revealedruns out of memory on the first0-click because nearly all10^10cells open at once. Instead, precompute the<= 9k(<= 900) mine and numbered cells, then apply coordinate compression: place every row within+-1of a mine (and any flagged row) in its own 1-row band and collapse each empty gap of rows between them into a single band, producing at most4k + 1 + 2frow bands and column bands (<= 401per axis whenk = 100, f = 0). Run 8-neighbor BFS over the resulting<= 160,801uniform rectangular blocks, adding(r2 - r1 + 1) * (c2 - c1 + 1)torevealed_safe_countinO(1)whenever a0-block opens, and replace full-gridprint_board()withprint_window(r0, c0, height, width)backed byO(log(k + f))binary search on band boundaries.
Follow-up questions
- How can you guarantee that the player's opening move is always safe and opens a clearing?
- How would you add a 'chord' action that opens all unflagged neighbors around an already-revealed number?
- How would you redesign flood fill and rendering when the grid is 100,000 by 100,000 with only 100 mines?
Similar questions
- Canonical Unix Path and Lazy Nested-List Iterator
- Email and Password Authentication Service
- Fixed-Stride Stream Iterator
- Find Extreme Dictionary by Dynamic Key
- 2D Max Pooling with Source Coordinates
- Time-Limited Credit Ledger