All questions

Minesweeper

Premium

Minesweeper

Build the classic Minesweeper on a 9x9 board with 10 hidden mines. It's a small game with one genuinely interesting algorithm at its heart: clicking an empty square doesn't reveal just that square, it opens up the whole connected region of blanks — a flood fill. This React version holds the board in useState and derives every cell's look from it.

Task

The starter App.tsx renders the board in its resting state — all 81 cells hidden, 🚩 10 remaining, a 🙂 reset button, and a "Click a cell" status. The mine positions are fixed (MINES) and each cell already knows its adjacent-mine count via buildBoard(). Make it playable:

  1. Hold the board in state. useState(buildBoard) plus a status of playing, won, or lost.
  2. Left-click reveals. A mine ends the game (reveal every mine, status lost). A numbered cell just shows its count. An empty (0-adjacent) cell flood-fills: reveal it and every connected 0-cell, plus the numbered border around them.
  3. Right-click flags. onContextMenu with e.preventDefault() toggles a 🚩 on a hidden cell.
  4. Detect the win. When every non-mine cell is revealed, status becomes won.
  5. Reset. The face button (🙂 / 😵 / 😎) rebuilds the board.

Examples

  • Click a cell in a wide-open area and a whole pocket of blanks opens at once, ringed by numbers — that's the flood fill.
  • Click a numbered cell and only that one square reveals; the number is how many of its 8 neighbors are mines.
  • Right-click a hidden cell to plant a flag; the 🚩 N counter drops by one. Right-click again to remove it.
  • Click a mine and every mine shows, the face turns 😵, and the status reads Lost.

Notes

  • Mines are fixed, not random. MINES is a hardcoded set of 10 indices so the board is deterministic — no Math.random.
  • Flood fill is the crux. Reveal numbered cells but never recurse through them, and track visited cells or you'll loop forever.
  • State is immutable. Each reveal builds a new board array; mutating cells in place won't re-render.
  • Styling (board grid, cell colors, number palette) is already in styles.css; focus on the state and the reveal logic.

Unlock the solution & editor

  • Runnable editor + tests

    Solve in the browser with instant Jest feedback.

  • Detailed solutions

    Walkthroughs, edge cases, and complexity notes.

  • Multi-framework variants

    React, Vue, Vanilla, Angular — same question, different stacks.

Upgrade to Premium