400/670

400. Minesweeper

Medium

You receive the state of a Minesweeper board — a grid board of characters where 'M' is a hidden mine and 'E' is a hidden empty square — plus the position (click_r, click_c) of the player's next click, which always lands on an 'M' or 'E' square. Apply one click and return the resulting board:

  • Clicking a mine ('M') ends the game: that square becomes 'X' and nothing else changes.
  • Clicking a hidden empty square ('E') reveals it. If one or more of its up-to-8 neighbors (sides and diagonals) hold mines, the square becomes the digit '1''8' counting those mines.
  • If none of its neighbors hold mines, the square becomes 'B' (revealed blank), and every hidden neighbor is revealed too, applying these same rules — the reveal ripples outward until it is walled in by digit squares.

The final board is uniquely determined by the click, so return exactly that grid.

One click, one flood of revealsThe click at (3, 0) sees no mines, so it opens as B and spreads to its neighbors. Squares adjacent to the mine at (1, 2) become '1' and stop the spread — the mine and the square above it are never reached.
before — click (3, 0)EEEEEEEMEEEEEEEEEEEEclickafterB1E1BB1M1BB111BBBBBBdigits fence in the mine; B squares had no mine in sight

Example 1:

Input: board = ["EEEEE", "EEMEE", "EEEEE", "EEEEE"], click = (3, 0)

Output: ["B1E1B", "B1M1B", "B111B", "BBBBB"]

Explanation: The click at (3, 0) touches no mine, so it opens as 'B' and the reveal spreads. It halts at the ring of squares that can see the mine at (1, 2) — those become '1'. The mine itself and the square directly above it stay hidden, because digit squares never propagate the reveal.

Example 2:

Input: board = ["EEEEE", "EEMEE", "EEEEE", "EEEEE"], click = (1, 2)

Output: ["EEEEE", "EEXEE", "EEEEE", "EEEEE"]

Explanation: The click lands directly on the mine, so it flips to 'X' and the rest of the board is untouched.

Constraints:

  • 1 ≤ m, n ≤ 50
  • Every board square is 'M' or 'E'
  • 0 ≤ click_r < m, 0 ≤ click_c < n
  • The clicked square is 'M' or 'E'

Hints:

Two of the three rules are single-square edits. The only interesting case is a clicked square with zero adjacent mines — that square opens a chain reaction over its neighbors. Chain reactions over grid neighbors are flood fill: DFS or BFS over the 8-connected grid graph.

Reveal a square exactly once. Count its adjacent mines first: a positive count writes a digit and STOPS the spread there; only a zero count writes 'B' and enqueues the still-hidden ('E') neighbors. Marking the square before processing its neighbors prevents revisits.

▶ Run checks these sample cases. Submit also runs hidden edge cases.

Input: board = ["EEEEE", "EEMEE", "EEEEE", "EEEEE"], click = (3, 0)

Expected output: ["B1E1B", "B1M1B", "B111B", "BBBBB"]