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:

  1. Minesweeper(m: int, n: int, k: int, seed: Optional[int] = None, bombs: Optional[Iterable[Tuple[int, int]]] = None)
    • Validate parameters: raise ValueError if m < 1, n < 1, k < 0, or k > m * n.
    • Store mine coordinates in self.bombs as a set of (row, col) tuples. When bombs is None, sample k distinct coordinates uniformly at random (reproducible when seed is given). When bombs is supplied, require exactly k distinct in-bounds coordinates (0 <= r < m, 0 <= c < n), raising ValueError otherwise.
  2. click(r: int, c: int) -> str
    • Raise IndexError if (r, c) lies outside 0 <= r < m or 0 <= 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 in self.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 count 0, automatically expand across all 8-connected 0-cells and reveal their surrounding numbered (1–8) border cells, never opening flagged cells.
    • Victory: As soon as all m * n - k safe cells have been revealed, set status to "won".
  3. toggle_flag(r: int, c: int) -> bool
    • Raise IndexError if (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. Return True if (r, c) is flagged afterward, False otherwise.
  4. print_board() -> str
    • Return m newline-separated lines, each containing n single-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).

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, n and 0 <= k <= m * n (otherwise __init__ raises ValueError).
  • Out-of-bounds (r, c) (including negative indices) must raise IndexError in click and toggle_flag.
  • Initialization must run in O(k) expected time and O(k) memory when k << m * n, and flood fill must be iterative so large open boards never hit Python's recursion limit.

Step-by-step walkthrough

  1. 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 all m * n - k safe 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 < m or 0 <= c < n raises IndexError; invalid board dimensions (m < 1, n < 1, or k outside [0, m * n]) raise ValueError.
    • 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, F flagged, 0–8 revealed count, and * for every mine once lost (overriding any flag placed on a mine).
    • Deterministic testing: Accept an optional seed for random placement and an optional bombs iterable to construct exact test boards.
  2. Pick sparse data structures instead of dense 2D grids

    A beginner's first design usually allocates two m x n 2D arrays (counts[m][n] and revealed[m][n]). That works for 10 x 10, but it pays O(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 with O(k + revealed + flagged). Caching each cell's neighbor mine count inside self.revealed at the moment it opens also means print_board never recomputes counts.

  3. Place k random bombs in O(k) time with flat-index sampling

    How do we choose k distinct cells uniformly at random without building a list of all m * n coordinates? Number the grid cells 0 .. m * n - 1 in row-major order, so flat number flat_index maps cleanly to row = flat_index // n and col = 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 lazy range object: when k is much smaller than m * n, it tracks chosen indices in a small temporary set rather than copying all m * n integers, keeping setup O(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 bombs
    
  4. Compute 8-direction neighbors and bomb counts on demand

    In Minesweeper, adjacency includes all 8 surrounding cells (horizontal, vertical, and diagonal). Isolating bounds checking inside _inside and _neighbors handles corners (3 neighbors) and edges (5 neighbors) in one place, and _count(r, c) computes the neighbor mine count on demand with at most 8 O(1) hash-set lookups in self.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 total
    
  5. Handle guard clauses and O(1) win detection in click

    click(r, c) checks every fast exit condition first: out-of-bounds raises IndexError; a finished game, revealed cell, or flagged cell returns self.status unchanged; a mine sets self.status = "lost".

    Only an unrevealed, unflagged safe cell reaches _flood_reveal(r, c). Because mines never enter self.revealed and each safe cell enters at most once, len(self.revealed) is the exact count of opened safe cells — making the win check a single O(1) comparison len(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.status
    
  6. Expand zero regions with breadth-first search (BFS) flood fill

    When a clicked cell has 0 neighbor mines, every one of its 8 neighbors is guaranteed safe, so Minesweeper automatically opens them too — and any neighbor that is also 0 continues 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-out deque queue).

    Three implementation details prevent subtle bugs:

    • Use an explicit deque, not recursion: On a 1000 x 1000 empty board (1,000,000 cells), recursive depth-first search overflows Python's 1000-frame call stack.
    • Mark self.revealed BEFORE appending to queue: Several 0-cells often share the same neighbor; recording it in self.revealed on 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 in self.revealed (so the numbered border shows on the board!), and continue skips 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  0
    
        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))
    
  7. Support flags, board rendering, and trace Example 1

    toggle_flag mutates self.flags only while "playing" and only on unrevealed cells. print_board formats each cell by checking _symbol in 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 4 board, 12 cells, k = 1 mine at (0, 3), 11 safe 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)
    
  8. Optimize for huge, sparse boards via coordinate compression

    Now consider the sparse-grid scaling challenge: m = n = 10^5 (10^10 cells!) with only k = 100 mines. Our sparse sets already make setup O(k) and numbered clicks O(1), saving ~10 GB of dense grid RAM. What still breaks? Almost the entire 10^5 x 10^5 board is one giant 0-ocean, so the very first click on a 0 cell tries to insert ~10^10 individual (r, c) tuples into self.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:

    1. Identify "interesting" rows and columns: Only rows br - 1, br, br + 1 around a mine (br, bc) (plus any flagged row fr) can ever hold a mine, a number 1..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. With k mines (and f = 0 flags), there are at most 3k single-row bands and k + 1 gap bands -> at most 4k + 1 bands per axis (<= 401 bands for k = 100!).
    2. Uniform blocks: Intersecting row bands with column bands partitions the 10^5 x 10^5 board into at most (4k + 1)^2 <= 160,801 blocks (or (4k + 1 + 2f)^2 with f flags):
      • Every multi-cell block has height or width >= 2 outside all mine neighborhoods, so every cell inside it has count 0.
      • Every 1 x 1 block is a single cell: either a mine, a flag, a numbered cell (1..8), or a 0 cell where one mine's row crosses a distant mine's column.
    3. BFS over blocks & viewport printing: Run the exact same 8-neighbor BFS on the block grid! Opening any 0 block adds its full rectangle area (r_end - r_start + 1) * (c_end - c_start + 1) to revealed_safe_count in O(1), bounding worst-case click time and memory to O((k + f)^2) regardless of m and n. Replace print_board() with print_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!]
    
  9. 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, records revealed[(2, 0)] = 0, and initializes queue = [(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 in self.flags.
  • When (0, 2) and (1, 2) pop, their count is 1 > 0, so they stay revealed on the border without expanding into (0, 3) (10 of 11 safe cells open -> "playing").
  • Calling toggle_flag(1, 3) followed by click(1, 3) opens (1, 3) (count = 1), bringing len(revealed) to 11 == 12 - 1 and immediately returning "won".

Complexity

  • Initialization (__init__): O(k) expected time and O(k) space when k is much smaller than m * n (up to O(m * n) when k approaches m * n), because random.sample(range(m * n), k) samples indices directly from the lazy range without building an m * n list.
  • 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 of R cells, O(R) time because each revealed cell enters and exits queue once and performs at most 8 neighbor checks plus one 8-lookup _count call; summed across an entire game, all click calls combined take at most O(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 the m * n cells.
  • Space: O(k + revealed + flagged) total game-state memory (bounded above by O(m * n)), avoiding upfront O(m * n) grid allocation.

Edge cases

  • Corners and edges: _neighbors filters through 0 <= nr < m and 0 <= nc < n, naturally yielding 3 neighbors at corners and 5 along edges.
  • Zero mines (k = 0) and all mines (k = m * n): With k = 0, any first click floods all m * n cells and returns "won"; with k = m * n, any click hits a mine and returns "lost".
  • 1 x 1 boards: 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 returns self.status.
  • Flags inside a zero region: _flood_reveal skips cell in self.flags, leaving the flagged cell closed until the player unflags and clicks it.
  • Negative coordinates (r = -1): Explicitly rejected by _inside with IndexError (whereas indexing a Python 2D list grid[-1][0] would silently read the last row!).
  • Duplicate or out-of-board custom bombs: Validated in __init__ by comparing len(bomb_list) and len(set(bomb_list)) against k and checking _inside on every coordinate.

Common mistakes

  • Marking cells revealed on popleft() instead of before append(): Up to 8 adjacent 0-cells can push the same unvisited neighbor into queue before 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 a 0-region; numbered cells must be added to self.revealed and 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 are 0).
  • Writing flood fill with recursion: Hits Python's recursion limit on boards larger than ~32 x 32 (1024 cells).
  • Scanning all m * n cells after every click to test for victory: Turns every single numbered click from O(1) into O(m * n).
  • Placing k mines via for _ in range(k): bombs.add(...) without resampling collisions: Duplicate random draws leave fewer than k mines on the board, breaking m * n - k win logic.

Alternative approaches

  • Precomputed dense m x n 2D arrays: Faster constant factors (grid[r][c] array indexing beats tuple hashing) and very clean for classic 30 x 16 boards, at the cost of mandatory O(m * n) initialization time and RAM.
  • Iterative depth-first search (explicit list stack instead of deque): Reveals the exact same connected region in O(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 k mines (and f flags) into at most 4k + 1 + 2f bands per axis so BFS runs in O((k + f)^2) block operations independent of m * n.

Follow-up questions

  • How can you guarantee that the player's opening move is always safe and opens a clearing? Defer _random_bombs until the first click(r0, c0) arrives (lazy initialization). Exclude (r0, c0) and its 8 neighbors (up to e <= 9 cells) from the candidate pool, sample k mines uniformly from the remaining m * n - e cells (for instance by drawing from range(m * n) and resampling any index inside the excluded 3 x 3 patch when k << m * n), and then run _flood_reveal(r0, c0). Validate upfront that k <= m * n - e (falling back to excluding only (r0, c0) when m * 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: if self.status != "playing" or (r, c) is not in self.revealed or self.revealed[(r, c)] == 0, return self.status. Otherwise count how many neighbors of (r, c) belong to self.flags; when that flag count equals self.revealed[(r, c)], call self.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.revealed runs out of memory on the first 0-click because nearly all 10^10 cells open at once. Instead, precompute the <= 9k (<= 900) mine and numbered cells, then apply coordinate compression: place every row within +-1 of 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 most 4k + 1 + 2f row bands and column bands (<= 401 per axis when k = 100, f = 0). Run 8-neighbor BFS over the resulting <= 160,801 uniform rectangular blocks, adding (r2 - r1 + 1) * (c2 - c1 + 1) to revealed_safe_count in O(1) whenever a 0-block opens, and replace full-grid print_board() with print_window(r0, c0, height, width) backed by O(log(k + f)) binary search on band boundaries.

Follow-up questions

Similar questions

More Bridge interview questions

All 5 Bridge questions →