KatInterview

Reveal Cells on a Mine Grid After a Tap

Trees & GraphsAuto-graded · 20 test cases
MediumAuto-gradedTrees & Graphsbfsflood-fillgrid

Last 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:

ValueMeaning
"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.

  1. Hidden mine ("M"): change it to "X". Nothing else changes.
  2. 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.
  3. 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 m rows and n columns, with 1 <= m, n <= 50.
  • tap is 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.