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:
- 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. - Clear square with nearby mines (
1to8mines among its 8 horizontal, vertical, and diagonal neighbors): Uncover only(row, col)to display its adjacent mine count'1'–'8', withlost = False. - Clear square with zero nearby mines (
0mines 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 also0(bordering numbered squares'1'–'8'are uncovered, but expansion does not continue past them), withlost = 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) <= 2001 <= len(board[0]) <= 200- Every string in
boardhas lengthlen(board[0])and consists solely of'.'and'*'. 0 <= row < len(board)and0 <= col < len(board[0])
Step-by-step walkthrough
Understand the grid layout, click outcomes, and output format
We receive a Minesweeper
boardas 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 = FalseDesign the state grids and 8-neighbor helper
Encapsulating the game inside a
Minesweeperclass letsclick,render, andprint_boardshare state cleanly without mutating the caller'sboardstrings:self.board: the original input strings (read-only), marking where mines ('*') sit.self.counts: arows x colsinteger matrix wherecounts[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: arows x colsboolean 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
_neighborshelper iteratesdrin(-1, 0, 1)anddcin(-1, 0, 1), skips(0, 0), and filters coordinates to0 <= nr < rowsand0 <= 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 countsKey idea: iterative BFS flood fill across zero cells
When
(row, col)is clear and has0surrounding mines, we uncover a connected region using a flood fill:- Why mines are never uncovered during expansion: if
(r, c)hascounts[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)hascounts[nr][nc] > 0, we uncover(nr, nc)so its warning digit shows, but do not enqueue it. Only neighbors withcounts[nr][nc] == 0propagate 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 200board (40,000zero cells), recursive DFS can nest nearly40,000frames deep and exceed Python's1,000-frame recursion limit, whereas iterative BFS withcollections.dequelives on the heap and never overflows. - Preventing duplicate visits: flip
self.revealed[nr][nc] = Truethe instant(nr, nc)is discovered, before pushing it ontoqueue, so adjacent zero cells never enqueue duplicates.
- Why mines are never uncovered during expansion: if
Implement `click`, `render`, and `print_board`
With those invariants ready,
click(row, col)evaluates the cases in order, andrender()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()))Trace flood-fill boundaries in detail
First check Example 1 (
board = ["*...", "....", "...."], click(2, 3)):(2, 3)starts at0, spreading across all eight0cells and uncovering(0, 1),(1, 0), and(1, 1)as'1'while(0, 0)stays'#'.Now look at a slightly trickier
4 x 5grid[".....", "..*..", ".....", "....."](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 0Notice safe cell
(0, 2)at the top center: its five neighbors are four1cells and the mine(1, 2). Because(0, 2)never touches a0cell, the flood fill never reaches it, leaving both(0, 2)and(1, 2)covered as'#'.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). InitializingMinesweeperscans allNcells and inspects at most 8 neighbors per cell (O(N)work). Duringclick, each cell flipsself.revealed[r][c]fromFalsetoTrueat 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, orO(1)when clicking a mine or numbered square). Finally,rendervisits each of theNcells once (O(N)). Across a multi-turn game reusing the sameMinesweeperinstance, allclickcalls combined still perform at mostO(N)total BFS work because an uncovered cell is never revisited. - Space:
O(N). Bothself.countsandself.revealedareR x Cmatrices (O(N)),renderallocatesNoutput characters (O(N)), andqueueholds at mostNzero-cell coordinates at once.
Edge cases
- Clicking directly on a mine (Example 2): only the clicked mine renders as
'*',lostbecomesTrue, 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] > 0returns right after settingself.revealed[row][col] = True, so only that single square displays its digit ('2'). - Grid with zero mines (
200 x 200open 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 only1s and'*', so no0cell 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 1grids: the bounds check0 <= nr < self.rows and 0 <= nc < self.colshandles 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 seenot self.revealed[nr][nc]before(nr, nc)is popped and push duplicate coordinates intoqueue, 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
boardlist: callers may hold a reference toboard; tracking visibility inself.revealedleaves 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
Minesweeperinstance alive across turns (and return early inclickifself.lostis alreadyTrue). In__init__, countself.unrevealed_safeas the total number of'.'squares on the board, and decrementself.unrevealed_safeevery time a clear square flipsself.revealed[r][c]toTrue; the player wins the instantself.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.flaggedboolean matrix of sizeR x C. Toggling a flag flipsself.flagged[r][c]inO(1)time whenevernot self.revealed[r][c];clickignores flagged squares so the player cannot accidentally detonate a marked cell, BFS skips flagged neighbors, andrenderemits'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.countsuntil the coordinates(first_r, first_c)of the opening click arrive. Then sample theMmine 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), computeself.countsonce inO(N), and resolve the click normally.
Follow-up questions
- How would you adapt the class for multi-turn play so win detection runs in O(1) per click?
- How would you add flag toggling ('F') so flagged cells are protected from accidental clicks?
- How can a Minesweeper engine guarantee that the opening click never detonates a mine?
Similar questions
- Grid State Update for a Minesweeper Click
- Object-Oriented Probabilistic Minesweeper Engine
- Asynchronous Courier Location Tracking Backend
- 2D Max Pooling with Source Coordinates
- Time-Limited Credit Ledger
- Grid Path Scoring with Streak Bonuses