Reveal Cells on a Mine Grid After a Tap
Trees & GraphsAuto-graded · 20 test casesLast updated
Simulate one tap on a minesweeper grid, using a flood fill from zero-count cells to reveal connected safe regions and their numbered borders.
Reveal Cells on a Mine Grid After a Tap
You are given the current state of a minesweeper board as a rectangular grid of single-character strings, and the position of one tap. Apply that tap and return the updated grid.
Each cell holds one of these values:
| Value | Meaning |
|---|---|
"M" | A hidden mine |
"E" | A hidden cell with no mine |
"B" | A revealed cell with no neighboring mines |
"1" to "8" | A revealed cell showing how many neighboring mines it has |
"X" | A revealed (detonated) mine |
Two cells are neighbors if they differ by at most one in both row and column, so each cell has up to 8 neighbors. Cells outside the grid do not count.
Tap rules
Let (r, c) be the tapped cell.
- Hidden mine (
"M"): change it to"X". Nothing else changes. - Hidden safe cell (
"E"): count the"M"cells among its neighbors.- If the count is greater than zero, replace the cell with that count as a digit string. The reveal stops there and does not spread.
- If the count is zero, replace the cell with
"B", then apply this same rule to every neighbor that is still"E". The reveal keeps spreading through zero-count cells, and numbered cells form its border.
- Any already revealed cell (
"B", a digit, or"X"): do nothing.
Mines are never revealed by spreading. They are only counted, and the only mine that changes is one that was tapped directly.
Task
Implement reveal_cells(grid, tap), where tap = [row, col] is a zero-indexed position. Return the grid after the tap has been fully applied. You may modify the input grid in place and return it, or return a new grid.
Constraints
- The grid has
mrows andncolumns, with1 <= m, n <= 50. tapis always a valid position inside the grid.- Every cell of the input is one of
"M","E","B", or a digit from"1"to"8". - Each row has the same length.
Examples
Example 1
Input: reveal_cells([['E', 'E'], ['E', 'M']], [0, 0])
Output: [['1', 'E'], ['E', 'M']]
Example 2
Input: reveal_cells([['B', '1', 'E', '1', 'B'], ['B', '1', 'M', '1', 'B']], [1, 2])
Output: [['B', '1', 'E', '1', 'B'], ['B', '1', 'X', '1', 'B']]
Hints
Hint 1
Handle the two simple cases first: tapping a mine, and tapping a cell that is not `"E"`. Only the hidden safe cell needs real work.
Hint 2
Treat cells as graph nodes with up to 8 neighbors. Start a BFS from the tapped cell, and only enqueue neighbors when the current cell has zero adjacent mines.
Hint 3
Mark a cell as visited the moment you enqueue it, for example by writing `"B"` into it, so it is never queued twice. Overwrite it with the digit once you dequeue it and know its count. Prefer BFS or an explicit stack over recursion, since a mine-free 50x50 grid can recurse about 2500 levels deep.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
This is a flood fill on a grid with a stopping rule.
- If the tapped cell is a mine (
"M"), turn it into"X"and return. - If the tapped cell is anything other than
"E"(already revealed), return the grid unchanged. - Otherwise run a BFS from the tapped cell, using a queue. For each cell taken from the queue:
- Count the neighboring
"M"cells, checking all 8 directions with bounds checks. - If the count is positive, write the digit into the cell. It is a border cell, so nothing is enqueued.
- If the count is zero, write
"B"and enqueue every neighbor that is still"E".
- Count the neighboring
A cell is marked "B" at the moment it is enqueued. This acts as a visited flag, so no other cell can enqueue it again, and no separate visited set is needed. When the cell is dequeued, its final value (a digit or "B") overwrites the marker.
I use BFS instead of recursion because a mine-free 50x50 grid can create a recursion chain around 2500 deep, which exceeds Python's default recursion limit.
Why it is correct
- Only
"E"cells are ever enqueued, so mines are never changed by spreading. They are only counted. - Overwriting
"E"with"B"or a digit never affects mine counts, because counting looks only for"M". - Spreading happens only from zero-count cells, and from each one it reaches every hidden neighbor. The result is the whole connected zero region plus its numbered border, which is exactly what the rules describe.
- Each cell leaves the
"E"state when it is enqueued, so it is processed at most once. - Revealed cells and the
"X"state are ignored by the early return and by the"E"check.
Complexity
- Time: O(m * n). Each cell is dequeued at most once, and each dequeue does a constant 8 neighbor checks.
- Space: O(m * n) in the worst case for the queue. The grid is modified in place.
Reference solution
from collections import deque
from typing import List
def reveal_cells(grid: List[List[str]], tap: List[int]) -> List[List[str]]:
row, col = tap
if grid[row][col] == 'M':
grid[row][col] = 'X'
return grid
if grid[row][col] != 'E':
return grid
rows, cols = len(grid), len(grid[0])
queue = deque([(row, col)])
grid[row][col] = 'B' # visited marker, set when enqueued
while queue:
r, c = queue.popleft()
mines = 0
neighbors = []
for dr in (-1, 0, 1):
for dc in (-1, 0, 1):
if dr == 0 and dc == 0:
continue
nr, nc = r + dr, c + dc
if 0 <= nr < rows and 0 <= nc < cols:
neighbors.append((nr, nc))
if grid[nr][nc] == 'M':
mines += 1
if mines:
grid[r][c] = str(mines)
else:
grid[r][c] = 'B'
for nr, nc in neighbors:
if grid[nr][nc] == 'E':
grid[nr][nc] = 'B'
queue.append((nr, nc))
return grid