KatInterview

Build a Minesweeper Engine That Scales to Huge Sparse Grids

Data Structure DesignModel answer
MediumModel answerData Structure Designdesignflood-fillbfs

Last updated

Design a Minesweeper class with board rendering and click handling via flood fill, then adapt it to enormous boards with few mines using lazy state and on-demand counting.

Build a Minesweeper engine for a grid with m rows and n columns. When a game starts, k mines are placed at random distinct cells.

Your class should offer these operations:

  1. render() returns a readable string of what the player currently sees. Covered cells appear as hidden. Uncovered cells show the number (0 to 8) of mines in their eight surrounding cells. Flag support is optional, but if you add it, keep the interface clear.
  2. click(r, c) uncovers a cell:
    • If the cell holds a mine, the game ends in a loss.
    • Otherwise the cell is uncovered. If its neighboring-mine count is 0, uncover the whole connected area of zero-count cells together with the numbered cells bordering it, following the usual Minesweeper rule.
    • Handle clicks on cells that are already uncovered, coordinates outside the grid, and clicks made after the game is over. Repeating a click must not change anything.

What to cover in your answer

  • The state you store and why.
  • The flood-fill algorithm you use and why it is safe on big boards.
  • Time and space complexity for each operation.
  • A set of test cases, including edge cases.

Follow-up: Suppose m and n are enormous but k is small. How would you make click() fast and keep memory low? Consider ideas such as generating the board lazily, using sparse structures, computing counts only when needed, caching, or limiting work, and discuss the trade-offs of each.

Hints

Hint 1

Separate hidden information (where the mines are) from player-visible information (which cells are uncovered or flagged). Ask whether either truly needs a full m by n array.

Hint 2

Use an iterative queue-based flood fill, and mark a cell as uncovered at the moment you enqueue it so it can never be queued twice. Only expand from cells whose count is 0.

Hint 3

For the huge-board follow-up, sample k distinct indices from range(m*n) instead of building the grid, store mines in a hash set, and compute a cell's count by checking its 8 neighbors on demand. Think about what the first click and a very large empty region do to your cost.