Skip to main content
MSH Logo

Minesweeper Algorithms Explained

Published on

Interactive Demo

Explore how Minesweeper algorithms work step by step:

Step 1: Building the Grid
The game starts with an empty grid. Each cell is hidden and ready to be filled.

Each gray cell is hidden and waiting to be revealed.

Core Algorithms

Mine Placement

Uses Fisher-Yates shuffle to randomly place mines, excluding the first-clicked cell to ensure the player never loses on their first move.

1const placeMines = (grid: Grid, mineCount: number, excludeRow: number, excludeCol: number): Grid => { 2 // Collect valid positions (excluding first click area) 3 const positions = []; 4 for (let row = 0; row < height; row++) { 5 for (let col = 0; col < width; col++) { 6 if (!(Math.abs(row - excludeRow) <= 1 && Math.abs(col - excludeCol) <= 1)) { 7 positions.push({ row, col }); 8 } 9 } 10 } 11 12 // Shuffle and place mines at first N positions 13 shuffle(positions); 14 positions.slice(0, mineCount).forEach(({ row, col }) => { 15 grid[row][col].isMine = true; 16 }); 17};

Neighbor Counting

Each cell counts adjacent mines in all 8 directions:

1const DIRECTIONS = [[-1,-1], [-1,0], [-1,1], [0,-1], [0,1], [1,-1], [1,0], [1,1]]; 2 3const countNeighborMines = (grid: Grid, row: number, col: number): number => { 4 return DIRECTIONS.reduce((count, [dr, dc]) => { 5 const r = row + dr, c = col + dc; 6 return count + (isInBounds(r, c) && grid[r][c].isMine ? 1 : 0); 7 }, 0); 8};

Flood Fill Reveal

When clicking an empty cell (0 adjacent mines), recursively reveal all connected empty cells:

1const reveal = (grid: Grid, row: number, col: number): void => { 2 if (!isInBounds(row, col) || grid[row][col].isRevealed) return; 3 4 grid[row][col].isRevealed = true; 5 6 // If empty cell, reveal all neighbors 7 if (grid[row][col].neighborMines === 0) { 8 DIRECTIONS.forEach(([dr, dc]) => reveal(grid, row + dr, col + dc)); 9 } 10};

This is the heart of Minesweeper - a depth-first search that spreads outward until it hits numbered cells.

Complexity

AlgorithmTimeSpace
Mine PlacementO(n)O(w×h)
Neighbor CountO(w×h)O(1)
Flood FillO(w×h)O(w×h)

Try It

Play the game: Minesweeper

References

GET IN TOUCH

Let's work together

I build fast, accessible, and delightful digital experiences for the web.
Whether you have a project in mind or just want to connect, I’d love to hear from you.

WRITE AN EMAIL

or reach out directly at hello@mohammadshehadeh.com