You are playing Minesweeper. The board is a grid of single characters: M is a hidden mine, E is a hidden empty square, B is an opened square with no mine around it, a digit 1 to 8 is an opened square showing how many of its 8 neighbours (across, up, down and diagonal) hold a mine, and X is a mine that has been opened.
You are also given click = [row, col], which is always a hidden square (M or E). Open it and return the board. Opening a mine turns it into X and nothing else happens. Opening an E with mines around it shows their count. Opening an E with no mines around it shows B and then opens every hidden neighbour by the same rules, which can spread far across the board.
Example 1
Input: board = EEEE click = [0, 3]
EMEE
EEEE
Output: EE1B
EM1B
EE1B
Why: the blank area spreads until the 1s wall it off2 more examples and the constraints
Example 2
Input: the same board, click = [1, 1]
Output: EEEE
EXEE
EEEE
Why: the click hits the mineExample 3
Input: the same board, click = [2, 0]
Output: EEEE
EMEE
1EEE
Why: one mine touches (2, 0), so only that square opensConstraints
- 1 ≤ rows, columns ≤ 50
- Each square is
M,E,Bor a digit1to8 - click points inside the board, at an
Mor anE
Your turn first
Have a go on paper or in your own editor, then reveal the approaches from the simplest up.
- Recursive reveal (DFS)O(m·n)
- Reveal with a queue (BFS)O(m·n)
The idea in one sentence
Side by side
| Approach | Time | Relative work for a 50 × 50 board | Verdict |
|---|---|---|---|
| Recursive reveal (DFS) | O(m·n) | Passes; deep recursion risk | |
| Reveal with a queue (BFS) | O(m·n) | Best; no call-stack limit |
m × n = size of the board.
Edge cases to test
- Click on a mine. Only that square changes, to
X. - Click next to a mine. The square shows a digit and nothing else opens.
- Board with no mines. One click opens every square as
B. - A 1 × 1 board. [["E"]] becomes [["B"]]; [["M"]] becomes [["X"]].
- Already opened squares.
Band digits already on the board are left as they are and never queued.
Common mistakes
- Spreading from a numbered square too, which opens squares that should stay hidden.
- Checking only 4 neighbours instead of all 8, so diagonal mines are missed.
- Marking a square only when it is popped, so it is queued many times.
How to talk through it
- 1Clarify. Do neighbours include diagonals? Can the click be on a mine? Is the board changed in place?
- 2Restate the rules. Mine: X. Mines around: digit, stop. None around: B, then open the hidden neighbours.
- 3Name the pattern. It is a flood fill where digits act as walls.
- 4Code BFS. Mark squares when queued; count mines when popped; spread only from blanks.
- 5Test out loud. Run a mine click, a digit click and a board with no mines.