Minesweeper Click Resolution and Board Rendering

Medium · Coding & Algorithms · Software Engineer · Technical Screen

Problem Statement

You are given an unrevealed Minesweeper grid board as a list of equal-length strings where '*' marks a mine and '.' marks a clear square, along with a 0-indexed coordinate (row, col) for the player's move. Initially, every square on the grid is covered.

Implement minesweeper_click_and_print(board: List[str], row: int, col: int) -> Dict[str, object] (along with a board-printing helper if structuring your solution as a class) to resolve that single click and format the visible board:

  1. Mine square (board[row][col] == '*'): Uncover (row, col) so it displays '*' and mark the game as lost (lost = True). Every other cell — including any other mines on the grid — stays covered.
  2. Clear square with nearby mines (1 to 8 mines among its 8 horizontal, vertical, and diagonal neighbors): Uncover only (row, col) to display its adjacent mine count '1'–'8', with lost = False.
  3. Clear square with zero nearby mines (0 mines among its 8 neighbors): Uncover (row, col) as '0' and uncover all in-bounds neighbors across all 8 directions, continuing outward from every newly uncovered square whose adjacent mine count is also 0 (bordering numbered squares '1'–'8' are uncovered, but expansion does not continue past them), with lost = False.

Render the resulting player view as a list of strings of the same dimensions using: - '#' for any cell that remains covered, - '*' for an uncovered mine, - '0'–'8' for an uncovered clear cell.

Return {"board": rendered_rows, "lost": lost}.

Examples

Example 1

Input:
  board = ["*...", "....", "...."]
  row = 2, col = 3

Output:
  {"board": ["#100", "1100", "0000"], "lost": False}

Walk-through: - Only (0, 0) holds a mine, so (0, 1), (1, 0), and (1, 1) each border 1 mine while all remaining safe squares border 0 mines. - Clicking (2, 3) uncovers a '0' cell, cascading through every connected '0' cell and uncovering the '1' ring at (0, 1), (1, 0), and (1, 1) while leaving (0, 0) covered as '#'.

Example 2

Input:
  board = ["..*", "*.."]
  row = 0, col = 2

Output:
  {"board": ["##*", "###"], "lost": True}

Walk-through: - Cell (0, 2) contains a mine, so clicking it uncovers only (0, 2) as '*' (leaving the other mine at (1, 0) hidden as '#') and sets lost to True.

Example 3

Input:
  board = ["..*", "*.."]
  row = 0, col = 1

Output:
  {"board": ["#2#", "###"], "lost": False}

Walk-through: - Safe square (0, 1) touches two mines ((0, 2) to the right and (1, 0) down-left). Because its adjacent count is 2 > 0, only (0, 1) uncovers as '2' and lost stays False.

Constraints

  • 1 <= len(board) <= 200
  • 1 <= len(board[0]) <= 200
  • Every string in board has length len(board[0]) and consists solely of '.' and '*'.
  • 0 <= row < len(board) and 0 <= col < len(board[0])

Step-by-step walkthrough

  1. Understand the grid layout, click outcomes, and output format

    We receive a Minesweeper board as a list of equal-length strings ('.' is a clear cell, '*' is a mine) with every cell initially covered, plus one click coordinate (row, col). We return {"board": [...], "lost": bool}, where "board" renders the player's view after the move:

    • '#' for any cell that stays covered,
    • '*' for an uncovered mine,
    • '0' through '8' for an uncovered clear cell, counting how many of its 8 surrounding neighbors (horizontal, vertical, and diagonal) hold mines.

    Here is how the three outcomes behave on the statement examples:

    Example 1 (0 nearby mines -> outward cascade stopping at numbered border):
      Input:  ["*...", "....", "...."], click (2, 3)
      Output: ["#100", "1100", "0000"], lost = False
    
    Example 2 (mine hit -> uncovers only that mine and ends the game):
      Input:  ["..*", "*.."], click (0, 2)
      Output: ["##*", "###"], lost = True
    
    Example 3 (positive count -> uncovers only that single cell):
      Input:  ["..*", "*.."], click (0, 1)
      Output: ["#2#", "###"], lost = False
    
  2. Design the state grids and 8-neighbor helper

    Encapsulating the game inside a Minesweeper class lets click, render, and print_board share state cleanly without mutating the caller's board strings:

    • self.board: the original input strings (read-only), marking where mines ('*') sit.
    • self.counts: a rows x cols integer matrix where counts[r][c] records how many mines sit in the 8 cells around (r, c). Computing this once avoids recounting neighbors during expansion or rendering.
    • self.revealed: a rows x cols boolean matrix (False = covered, True = uncovered) that doubles as our visited set during graph search.
    • self.lost: a boolean recording whether a mine was detonated.

    A small _neighbors helper iterates dr in (-1, 0, 1) and dc in (-1, 0, 1), skips (0, 0), and filters coordinates to 0 <= nr < rows and 0 <= nc < cols:

    The 8 neighbor offsets (dr, dc) around (r, c):
      (-1, -1)   (-1,  0)   (-1, +1)
      ( 0, -1)    (r, c)    ( 0, +1)
      (+1, -1)   (+1,  0)   (+1, +1)
    
    from typing import Any, Dict, List, Optional, Set, Tuple
    from collections import deque
    
    MINE = "*"
    HIDDEN = "#"
    
    
    class Minesweeper:
        def __init__(self, board: List[str]):
            # board: read-only list of row strings where '*' is a mine and '.' is safe
            self.board = board
            self.rows = len(board)
            self.cols = len(board[0]) if board else 0
            # counts: 2D int grid where counts[r][c] is the number of mines in the 8 neighbors of (r, c)
            self.counts = self._count_all_mines()
            # revealed: 2D bool grid tracking which cells are visible; also acts as our BFS visited set
            self.revealed = [[False] * self.cols for _ in range(self.rows)]
            self.lost = False
    
        def _neighbors(self, r: int, c: int) -> List[Tuple[int, int]]:
            """Return all in-bounds coordinates among the 8 cells surrounding (r, c)."""
            result: List[Tuple[int, int]] = []
            for dr in (-1, 0, 1):
                for dc in (-1, 0, 1):
                    # Skip (0, 0) because a cell is not a neighbor of itself.
                    if dr == 0 and dc == 0:
                        continue
                    nr, nc = r + dr, c + dc
                    # Bounds check handles corners (3 neighbors), edges (5), and 1D boards cleanly.
                    if 0 <= nr < self.rows and 0 <= nc < self.cols:
                        result.append((nr, nc))
            return result
    
        def _count_all_mines(self) -> List[List[int]]:
            """Precompute the 8-directional adjacent mine count for every cell once."""
            counts = [[0] * self.cols for _ in range(self.rows)]
            for r in range(self.rows):
                for c in range(self.cols):
                    for nr, nc in self._neighbors(r, c):
                        if self.board[nr][nc] == MINE:
                            counts[r][c] += 1
            return counts
    
  3. Key idea: iterative BFS flood fill across zero cells

    When (row, col) is clear and has 0 surrounding mines, we uncover a connected region using a flood fill:

    • Why mines are never uncovered during expansion: if (r, c) has counts[r][c] == 0, none of its 8 neighbors contains a mine, so every neighbor is safe to uncover.
    • Where expansion stops: when a neighbor (nr, nc) has counts[nr][nc] > 0, we uncover (nr, nc) so its warning digit shows, but do not enqueue it. Only neighbors with counts[nr][nc] == 0 propagate further.
    • Why iterative BFS over recursive DFS: both Breadth-First Search (BFS) (layer-by-layer with a first-in, first-out queue) and Depth-First Search (DFS) (nested recursion) uncover the exact same cells. On an open 200 x 200 board (40,000 zero cells), recursive DFS can nest nearly 40,000 frames deep and exceed Python's 1,000-frame recursion limit, whereas iterative BFS with collections.deque lives on the heap and never overflows.
    • Preventing duplicate visits: flip self.revealed[nr][nc] = True the instant (nr, nc) is discovered, before pushing it onto queue, so adjacent zero cells never enqueue duplicates.
  4. Implement `click`, `render`, and `print_board`

    With those invariants ready, click(row, col) evaluates the cases in order, and render() maps each cell to '#', '*', or '0'–'8':

        def click(self, row: int, col: int) -> bool:
            """Apply one click at (row, col). Return True if this click hit a mine."""
            # Ignore clicks on cells that were already uncovered earlier in the game.
            if self.revealed[row][col]:
                return False
    
            self.revealed[row][col] = True
    
            # Rule 1: Clicking a mine reveals that mine and loses the game immediately.
            if self.board[row][col] == MINE:
                self.lost = True
                return True
    
            # Rule 3: Clicking a cell with >= 1 adjacent mines reveals only its count and stops.
            if self.counts[row][col] > 0:
                return False
    
            # Rule 2: Clicking a 0-mine cell triggers a BFS flood fill across connected 0-mine cells.
            # queue: FIFO deque of revealed (r, c) coordinates whose adjacent mine count is 0
            queue = deque([(row, col)])
            while queue:
                r, c = queue.popleft()
                # Since counts[r][c] == 0, none of its 8 neighbors can be a mine, so all are safe to reveal.
                for nr, nc in self._neighbors(r, c):
                    if not self.revealed[nr][nc]:
                        # Mark revealed immediately on discovery so other 0-neighbors never enqueue duplicates.
                        self.revealed[nr][nc] = True
                        # Only 0-mine neighbors keep spreading; numbered neighbors form the visible border.
                        if self.counts[nr][nc] == 0:
                            queue.append((nr, nc))
            return False
    
        def render(self) -> List[str]:
            """Format the current player view: '#' hidden, '*' revealed mine, '0'-'8' revealed safe cell."""
            lines: List[str] = []
            for r in range(self.rows):
                row_chars: List[str] = []
                for c in range(self.cols):
                    if not self.revealed[r][c]:
                        row_chars.append(HIDDEN)
                    elif self.board[r][c] == MINE:
                        row_chars.append(MINE)
                    else:
                        row_chars.append(str(self.counts[r][c]))
                lines.append("".join(row_chars))
            return lines
    
        def print_board(self) -> None:
            """Print the rendered board rows separated by newlines."""
            print("\n".join(self.render()))
    
  5. Trace flood-fill boundaries in detail

    First check Example 1 (board = ["*...", "....", "...."], click (2, 3)): (2, 3) starts at 0, spreading across all eight 0 cells and uncovering (0, 1), (1, 0), and (1, 1) as '1' while (0, 0) stays '#'.

    Now look at a slightly trickier 4 x 5 grid [".....", "..*..", ".....", "....."] (mine at (1, 2)) clicked at (3, 0):

    Input board          Precomputed counts      After click(3, 0)
    . . . . .            0 1 1 1 0               0 1 # 1 0
    . . * . .    --->    0 1 0 1 0      --->     0 1 # 1 0
    . . . . .            0 1 1 1 0               0 1 1 1 0
    . . . . .            0 0 0 0 0               0 0 0 0 0
    

    Notice safe cell (0, 2) at the top center: its five neighbors are four 1 cells and the mine (1, 2). Because (0, 2) never touches a 0 cell, the flood fill never reaches it, leaving both (0, 2) and (1, 2) covered as '#'.

  6. Complete solution

    from typing import Any, Dict, List, Optional, Set, Tuple
    from collections import deque
    
    MINE = "*"
    HIDDEN = "#"
    
    
    class Minesweeper:
        def __init__(self, board: List[str]):
            # board: read-only list of row strings where '*' is a mine and '.' is safe
            self.board = board
            self.rows = len(board)
            self.cols = len(board[0]) if board else 0
            # counts: 2D int grid where counts[r][c] is the number of mines in the 8 neighbors of (r, c)
            self.counts = self._count_all_mines()
            # revealed: 2D bool grid tracking which cells are visible; also acts as our BFS visited set
            self.revealed = [[False] * self.cols for _ in range(self.rows)]
            self.lost = False
    
        def _neighbors(self, r: int, c: int) -> List[Tuple[int, int]]:
            """Return all in-bounds coordinates among the 8 cells surrounding (r, c)."""
            result: List[Tuple[int, int]] = []
            for dr in (-1, 0, 1):
                for dc in (-1, 0, 1):
                    # Skip (0, 0) because a cell is not a neighbor of itself.
                    if dr == 0 and dc == 0:
                        continue
                    nr, nc = r + dr, c + dc
                    # Bounds check handles corners (3 neighbors), edges (5), and 1D boards cleanly.
                    if 0 <= nr < self.rows and 0 <= nc < self.cols:
                        result.append((nr, nc))
            return result
    
        def _count_all_mines(self) -> List[List[int]]:
            """Precompute the 8-directional adjacent mine count for every cell once."""
            counts = [[0] * self.cols for _ in range(self.rows)]
            for r in range(self.rows):
                for c in range(self.cols):
                    for nr, nc in self._neighbors(r, c):
                        if self.board[nr][nc] == MINE:
                            counts[r][c] += 1
            return counts
    
        def click(self, row: int, col: int) -> bool:
            """Apply one click at (row, col). Return True if this click hit a mine."""
            # Ignore clicks on cells that were already uncovered earlier in the game.
            if self.revealed[row][col]:
                return False
    
            self.revealed[row][col] = True
    
            # Rule 1: Clicking a mine reveals that mine and loses the game immediately.
            if self.board[row][col] == MINE:
                self.lost = True
                return True
    
            # Rule 3: Clicking a cell with >= 1 adjacent mines reveals only its count and stops.
            if self.counts[row][col] > 0:
                return False
    
            # Rule 2: Clicking a 0-mine cell triggers a BFS flood fill across connected 0-mine cells.
            # queue: FIFO deque of revealed (r, c) coordinates whose adjacent mine count is 0
            queue = deque([(row, col)])
            while queue:
                r, c = queue.popleft()
                # Since counts[r][c] == 0, none of its 8 neighbors can be a mine, so all are safe to reveal.
                for nr, nc in self._neighbors(r, c):
                    if not self.revealed[nr][nc]:
                        # Mark revealed immediately on discovery so other 0-neighbors never enqueue duplicates.
                        self.revealed[nr][nc] = True
                        # Only 0-mine neighbors keep spreading; numbered neighbors form the visible border.
                        if self.counts[nr][nc] == 0:
                            queue.append((nr, nc))
            return False
    
        def render(self) -> List[str]:
            """Format the current player view: '#' hidden, '*' revealed mine, '0'-'8' revealed safe cell."""
            lines: List[str] = []
            for r in range(self.rows):
                row_chars: List[str] = []
                for c in range(self.cols):
                    if not self.revealed[r][c]:
                        row_chars.append(HIDDEN)
                    elif self.board[r][c] == MINE:
                        row_chars.append(MINE)
                    else:
                        row_chars.append(str(self.counts[r][c]))
                lines.append("".join(row_chars))
            return lines
    
        def print_board(self) -> None:
            """Print the rendered board rows separated by newlines."""
            print("\n".join(self.render()))
    
    
    def minesweeper_click_and_print(board: List[str], row: int, col: int) -> Dict[str, object]:
        game = Minesweeper(board)
        lost = game.click(row, col)
        return {"board": game.render(), "lost": lost}
    

    ✅ Submit now — all tests should pass.

Intuition & how it works

Imagine pouring water onto a flat tabletop where low numbered walls surround hidden mines. If you pour water onto a completely clear tile (0 nearby mines), the water flows outward in all 8 directions across connected clear tiles, wets the first ring of numbered walls it touches, and stops right at those walls so it never reaches any mine behind them. Uncovering a connected region like this is a flood fill, implemented here with Breadth-First Search (BFS) — a graph traversal that explores cells layer by layer using a FIFO queue (a first-in, first-out line where the earliest queued cell is processed first), rather than Depth-First Search (DFS), which dives down a single path recursively before backtracking.

Why do simpler-looking implementations fail? Writing a recursive DFS is tempting, but on an open 200 x 200 grid with 40,000 zero cells, recursion can nest nearly 40,000 calls deep and crash past Python's 1,000-frame recursion limit. Second, if your traversal continues expanding from numbered cells (1–8) instead of stopping there, the flood leaks across the numbered border and uncovers mines or disconnected safe pockets. Third, if you mark cells revealed when popping from the queue instead of when enqueueing, up to 8 zero-neighbors can push duplicate copies of the same coordinate into the queue.

Let's trace Example 1 (board = ["*...", "....", "...."], mine at (0, 0)) when clicking (2, 3):

Hidden grid        Adjacent mine counts      Click (2, 3) -> BFS from (2, 3)
* . . .            * 1 0 0                   1. (2,3) has count 0 -> reveal & queue [(2,3)]
. . . .            1 1 0 0                   2. BFS spreads across all eight '0' cells in
. . . .            0 0 0 0                      cols 2-3 and row 2
                                             3. Bordering '1' cells (0,1), (1,0), (1,1) are
                                                revealed, NOT queued; (0,0) stays '#'
                                             4. Rendered view: ["#100", "1100", "0000"],
                                                lost = False

Complexity

Let R be the number of rows, C be the number of columns, and N = R * C be the total number of cells.

  • Time: O(N). Initializing Minesweeper scans all N cells and inspects at most 8 neighbors per cell (O(N) work). During click, each cell flips self.revealed[r][c] from False to True at most once, so each zero cell enters and leaves the FIFO queue at most once and inspects at most 8 neighbors (O(N) worst case on an open grid, or O(1) when clicking a mine or numbered square). Finally, render visits each of the N cells once (O(N)). Across a multi-turn game reusing the same Minesweeper instance, all click calls combined still perform at most O(N) total BFS work because an uncovered cell is never revisited.
  • Space: O(N). Both self.counts and self.revealed are R x C matrices (O(N)), render allocates N output characters (O(N)), and queue holds at most N zero-cell coordinates at once.

Edge cases

  • Clicking directly on a mine (Example 2): only the clicked mine renders as '*', lost becomes True, and any other mines on the board remain '#' (such as (1, 0) in Example 2).
  • Clicking a numbered clear square (Example 3): self.counts[row][col] > 0 returns right after setting self.revealed[row][col] = True, so only that single square displays its digit ('2').
  • Grid with zero mines (200 x 200 open board): one click uncovers every square as '0' without hitting Python's recursion limit.
  • Clear squares surrounded only by digits and mines: in [".....", "..*..", ".....", "....."] clicked at (3, 0), square (0, 2) borders only 1s and '*', so no 0 cell ever reaches it and it stays '#'.
  • Diagonal mines and maximum count 8: diagonal mines count toward adjacency, so a clear square ringed by 8 mines displays '8'.
  • Corners, edges, 1-row, 1-column, and 1 x 1 grids: the bounds check 0 <= nr < self.rows and 0 <= nc < self.cols handles cells with 0, 1, 2, 3, or 5 neighbors uniformly.

Common mistakes

  • Marking cells revealed on popleft() instead of when enqueueing: multiple adjacent zero cells see not self.revealed[nr][nc] before (nr, nc) is popped and push duplicate coordinates into queue, inflating queue size and work by up to 8x.
  • Expanding from numbered squares (counts > 0): numbered squares must be uncovered as the visible boundary of a zero region, not expanded further; expanding from them uncovers mines or unrelated safe regions across the grid.
  • Checking only 4 orthogonal neighbors instead of all 8: skipping diagonals undercounts nearby mines and lets the flood fill leak diagonally past mines.
  • Uncovering every mine on loss: hitting a mine uncovers that clicked square and reports lost = True; unclicked mines remain '#'.
  • Mutating the input board list: callers may hold a reference to board; tracking visibility in self.revealed leaves the input untouched.

Follow-up questions

  • How would you adapt the class for multi-turn play so win detection runs in O(1) per click? Keep one Minesweeper instance alive across turns (and return early in click if self.lost is already True). In __init__, count self.unrevealed_safe as the total number of '.' squares on the board, and decrement self.unrevealed_safe every time a clear square flips self.revealed[r][c] to True; the player wins the instant self.unrevealed_safe == 0, with no board scan needed.
  • How would you add flag toggling ('F') so flagged cells are protected from accidental clicks? Maintain a self.flagged boolean matrix of size R x C. Toggling a flag flips self.flagged[r][c] in O(1) time whenever not self.revealed[r][c]; click ignores flagged squares so the player cannot accidentally detonate a marked cell, BFS skips flagged neighbors, and render emits 'F' for covered flagged squares.
  • How can a Minesweeper engine guarantee that the opening click never detonates a mine? Defer placing mines and computing self.counts until the coordinates (first_r, first_c) of the opening click arrive. Then sample the M mine positions uniformly at random from all grid coordinates excluding (first_r, first_c) (and optionally excluding its 8 neighbors too so the opening click is guaranteed to be a '0' that opens a playable area), compute self.counts once in O(N), and resolve the click normally.

Follow-up questions

Similar questions

More Nash AI interview questions

All 4 Nash AI questions →