Minesweeper
Minesweeper is a medium graphs problem solved with the matrix graphs pattern.
The best approach, optimal (bfs reveal with a queue), runs in O(m · n) time and O(m · n) space.
Below are 3 approaches in Java, Python, C++ and JavaScript, from brute force (repeated sweeps) up.
Problem
You are playing the classic mine-hunting game on an m x n board of characters:
'M'is a hidden mine and'E'is a hidden empty cell.'B'is an empty cell that is already revealed and has no mine among its up to 8 neighbours (above, below, left, right and the four diagonals).- A digit
'1'to'8'is a revealed cell that shows how many mines are among its neighbours. 'X'is a mine that has been revealed.
You also get click = [r, c], the position of the next click. That cell is hidden: it is 'M' or 'E'. Apply the click with these rules and return the board:
- If a mine
'M'is clicked, it becomes'X'. The game is over and nothing else changes. - If an empty cell
'E'with no adjacent mines is revealed, it becomes'B', and all of its hidden neighbours are revealed too, by these same rules. - If an empty cell
'E'with at least one adjacent mine is revealed, it becomes the digit for that count, and its neighbours are not revealed.
Stop when no more cells can be revealed this way.
Examples
Example 1
- Input
board = [[E,E,E,E,E],[E,E,E,E,E],[E,M,E,E,E],[E,E,E,E,M]], click = [0,4]- Output
[[B,B,B,B,B],[1,1,1,B,B],[E,M,1,1,1],[E,E,E,E,M]]- Why
- The clicked corner has no mine around it, so it becomes B and the reveal spreads to its neighbours. It keeps spreading through blank cells and stops at the cells that touch a mine, which show their counts. The cells behind that wall of numbers stay hidden.
Example 2
- Input
board = [[B,B,B,B,B],[1,1,1,B,B],[E,M,1,1,1],[E,E,E,E,M]], click = [2,1]- Output
[[B,B,B,B,B],[1,1,1,B,B],[E,X,1,1,1],[E,E,E,E,M]]- Why
- The click hits a mine. It turns into X, the game is over, and nothing else changes.
Example 3
- Input
board = [[B,B,B,B,B],[1,1,1,B,B],[E,M,1,1,1],[E,E,E,E,M]], click = [3,3]- Output
[[B,B,B,B,B],[1,1,1,B,B],[E,M,1,1,1],[E,E,E,1,M]]- Why
- Cell (3,3) touches the mine at (3,4), so it shows 1. A cell with a number does not reveal its neighbours.
Constraints
m == board.length,n == board[i].length1 <= m, n <= 50- Every cell of
boardis'M','E','B'or a digit from'1'to'8'. click.length == 2,0 <= click[0] < m,0 <= click[1] < nboard[click[0]][click[1]]is'M'or'E'.
Solve it here
Write your solution in Java, Python, C++ or JavaScript and run it against the examples, right in the page. Submit runs the hidden tests too and, with a free account, records the solve in your revision log.
Your own testcases: Run checks these, and the expected output comes from our reference solution.
My submissions
Nothing yet. Every Run and Submit you make while signed in shows up here.
| When | Result | Tests | Runtime | Your time | Type |
|---|
Run checks the testcases above (3 examples, or your own). Submit also runs 13 hidden tests and saves the solve to your log. Signed in, every Run and Submit is saved under My submissions; your draft stays in this browser.
Animated walkthrough
A narrated, step-by-step animation that builds the solution from the idea up. Press play, or step through it at your own pace.
Concepts first, then the problem and every approach, step by step.
Space to play or pause · ← → to jump a step · click or drag the bar to seek
Solutions
Try it yourself first. Then compare: each approach lists its idea, the steps, its time and space, and the code in Java, Python, C++ and JavaScript.
| Approach | Time | Space |
|---|---|---|
| Brute force (repeated sweeps) | O((m · n)²) | O(m · n) |
| DFS reveal (recursion) | O(m · n) | O(m · n) |
| Optimal (BFS reveal with a queue) | O(m · n) | O(m · n) |
1Brute force (repeated sweeps)
O((m · n)²)A sweep visits all m · n cells with nine checks each. The opened area can grow by as little as one ring of cells per sweep, so a winding blank area may need O(m · n) sweeps.O(m · n)The boolean grid of opened cells has m · n entries.Do the reveal in rounds without any recursion or queue. First open the clicked cell: a mine becomes X and we stop, otherwise it gets its count, or B when the count is zero. Then sweep the whole board again and again. In each sweep, every blank cell opened by this click opens all of its still hidden neighbours. When a full sweep opens nothing new, the reveal is complete. A boolean grid remembers which cells this click opened, so blanks from earlier clicks are not touched.
- If the clicked cell is 'M', set it to 'X' and return the board.
- Open the clicked cell: set it to its mine count, or 'B' if the count is zero, and mark it opened.
- Repeat sweeps while something changed: for every opened cell that is 'B', open each neighbour that is still 'E' the same way and note the change.
- Return the board.
class Solution {
public char[][] updateBoard(char[][] board, int[] click) {
int m = board.length, n = board[0].length;
int r0 = click[0], c0 = click[1];
if (board[r0][c0] == 'M') {
board[r0][c0] = 'X';
return board;
}
boolean[][] opened = new boolean[m][n];
board[r0][c0] = cellValue(board, r0, c0);
opened[r0][c0] = true;
boolean changed = true;
while (changed) {
changed = false;
for (int r = 0; r < m; r++) {
for (int c = 0; c < n; c++) {
if (!opened[r][c] || board[r][c] != 'B') continue;
for (int dr = -1; dr <= 1; dr++) {
for (int dc = -1; dc <= 1; dc++) {
int nr = r + dr, nc = c + dc;
if (nr >= 0 && nc >= 0 && nr < m && nc < n && board[nr][nc] == 'E') {
board[nr][nc] = cellValue(board, nr, nc);
opened[nr][nc] = true;
changed = true;
}
}
}
}
}
}
return board;
}
private char cellValue(char[][] board, int r, int c) {
int mines = 0;
for (int dr = -1; dr <= 1; dr++) {
for (int dc = -1; dc <= 1; dc++) {
int nr = r + dr, nc = c + dc;
if (nr >= 0 && nc >= 0 && nr < board.length && nc < board[0].length && board[nr][nc] == 'M') mines++;
}
}
return mines == 0 ? 'B' : (char) ('0' + mines);
}
}class Solution:
def updateBoard(self, board: List[List[str]], click: List[int]) -> List[List[str]]:
m, n = len(board), len(board[0])
r0, c0 = click
if board[r0][c0] == 'M':
board[r0][c0] = 'X'
return board
opened = [[False] * n for _ in range(m)]
board[r0][c0] = self.cellValue(board, r0, c0)
opened[r0][c0] = True
changed = True
while changed:
changed = False
for r in range(m):
for c in range(n):
if not opened[r][c] or board[r][c] != 'B':
continue
for dr in (-1, 0, 1):
for dc in (-1, 0, 1):
nr, nc = r + dr, c + dc
if 0 <= nr < m and 0 <= nc < n and board[nr][nc] == 'E':
board[nr][nc] = self.cellValue(board, nr, nc)
opened[nr][nc] = True
changed = True
return board
def cellValue(self, board: List[List[str]], r: int, c: int) -> str:
mines = 0
for dr in (-1, 0, 1):
for dc in (-1, 0, 1):
nr, nc = r + dr, c + dc
if 0 <= nr < len(board) and 0 <= nc < len(board[0]) and board[nr][nc] == 'M':
mines += 1
return 'B' if mines == 0 else str(mines)class Solution {
public:
vector<vector<char>> updateBoard(vector<vector<char>>& board, vector<int>& click) {
int m = board.size(), n = board[0].size();
int r0 = click[0], c0 = click[1];
if (board[r0][c0] == 'M') {
board[r0][c0] = 'X';
return board;
}
vector<vector<bool>> opened(m, vector<bool>(n, false));
board[r0][c0] = cellValue(board, r0, c0);
opened[r0][c0] = true;
bool changed = true;
while (changed) {
changed = false;
for (int r = 0; r < m; r++) {
for (int c = 0; c < n; c++) {
if (!opened[r][c] || board[r][c] != 'B') continue;
for (int dr = -1; dr <= 1; dr++) {
for (int dc = -1; dc <= 1; dc++) {
int nr = r + dr, nc = c + dc;
if (nr >= 0 && nc >= 0 && nr < m && nc < n && board[nr][nc] == 'E') {
board[nr][nc] = cellValue(board, nr, nc);
opened[nr][nc] = true;
changed = true;
}
}
}
}
}
}
return board;
}
private:
char cellValue(vector<vector<char>>& board, int r, int c) {
int mines = 0;
for (int dr = -1; dr <= 1; dr++) {
for (int dc = -1; dc <= 1; dc++) {
int nr = r + dr, nc = c + dc;
if (nr >= 0 && nc >= 0 && nr < (int) board.size() && nc < (int) board[0].size() && board[nr][nc] == 'M') mines++;
}
}
return mines == 0 ? 'B' : (char) ('0' + mines);
}
};function updateBoard(board, click) {
const m = board.length, n = board[0].length;
const [r0, c0] = click;
if (board[r0][c0] === 'M') {
board[r0][c0] = 'X';
return board;
}
const opened = Array.from({ length: m }, () => new Array(n).fill(false));
board[r0][c0] = cellValue(r0, c0);
opened[r0][c0] = true;
let changed = true;
while (changed) {
changed = false;
for (let r = 0; r < m; r++) {
for (let c = 0; c < n; c++) {
if (!opened[r][c] || board[r][c] !== 'B') continue;
for (let dr = -1; dr <= 1; dr++) {
for (let dc = -1; dc <= 1; dc++) {
const nr = r + dr, nc = c + dc;
if (nr >= 0 && nc >= 0 && nr < m && nc < n && board[nr][nc] === 'E') {
board[nr][nc] = cellValue(nr, nc);
opened[nr][nc] = true;
changed = true;
}
}
}
}
}
}
return board;
function cellValue(r, c) {
let mines = 0;
for (let dr = -1; dr <= 1; dr++) {
for (let dc = -1; dc <= 1; dc++) {
const nr = r + dr, nc = c + dc;
if (nr >= 0 && nc >= 0 && nr < m && nc < n && board[nr][nc] === 'M') mines++;
}
}
return mines === 0 ? 'B' : String(mines);
}
}2DFS reveal (recursion)
O(m · n)Each cell changes from 'E' at most once, and handling it costs a constant number of neighbour checks (eight for the count, eight calls).O(m · n)The recursion can be as deep as the number of blank cells, up to m · n when the board has no mines.The reveal is a flood fill over the eight directions. reveal(r, c) returns at once for a cell outside the board or one that is not 'E'. Otherwise it counts the mines around the cell. With a positive count the cell shows that digit and the spreading stops there. With zero the cell becomes 'B' and reveal is called on all eight neighbours. A cell stops being 'E' the moment it is handled, which is what keeps the recursion from visiting it twice.
- If the clicked cell is 'M', set it to 'X' and return.
- Otherwise call reveal(click[0], click[1]).
- reveal: skip cells outside the board or not 'E'. Count the adjacent 'M' cells.
- If the count is positive, write the digit and return. Otherwise write 'B' and call reveal on the eight neighbours.
class Solution {
public char[][] updateBoard(char[][] board, int[] click) {
int r = click[0], c = click[1];
if (board[r][c] == 'M') {
board[r][c] = 'X';
return board;
}
reveal(board, r, c);
return board;
}
private void reveal(char[][] board, int r, int c) {
if (r < 0 || c < 0 || r >= board.length || c >= board[0].length || board[r][c] != 'E') return;
int mines = countMines(board, r, c);
if (mines > 0) {
board[r][c] = (char) ('0' + mines);
return;
}
board[r][c] = 'B';
for (int dr = -1; dr <= 1; dr++) {
for (int dc = -1; dc <= 1; dc++) {
if (dr != 0 || dc != 0) reveal(board, r + dr, c + dc);
}
}
}
private int countMines(char[][] board, int r, int c) {
int count = 0;
for (int dr = -1; dr <= 1; dr++) {
for (int dc = -1; dc <= 1; dc++) {
int nr = r + dr, nc = c + dc;
if (nr >= 0 && nc >= 0 && nr < board.length && nc < board[0].length && board[nr][nc] == 'M') count++;
}
}
return count;
}
}class Solution:
def updateBoard(self, board: List[List[str]], click: List[int]) -> List[List[str]]:
sys.setrecursionlimit(10000)
r, c = click
if board[r][c] == 'M':
board[r][c] = 'X'
return board
self.reveal(board, r, c)
return board
def reveal(self, board: List[List[str]], r: int, c: int) -> None:
if r < 0 or c < 0 or r >= len(board) or c >= len(board[0]) or board[r][c] != 'E':
return
mines = self.countMines(board, r, c)
if mines > 0:
board[r][c] = str(mines)
return
board[r][c] = 'B'
for dr in (-1, 0, 1):
for dc in (-1, 0, 1):
if dr != 0 or dc != 0:
self.reveal(board, r + dr, c + dc)
def countMines(self, board: List[List[str]], r: int, c: int) -> int:
count = 0
for dr in (-1, 0, 1):
for dc in (-1, 0, 1):
nr, nc = r + dr, c + dc
if 0 <= nr < len(board) and 0 <= nc < len(board[0]) and board[nr][nc] == 'M':
count += 1
return countclass Solution {
public:
vector<vector<char>> updateBoard(vector<vector<char>>& board, vector<int>& click) {
int r = click[0], c = click[1];
if (board[r][c] == 'M') {
board[r][c] = 'X';
return board;
}
reveal(board, r, c);
return board;
}
private:
void reveal(vector<vector<char>>& board, int r, int c) {
if (r < 0 || c < 0 || r >= (int) board.size() || c >= (int) board[0].size() || board[r][c] != 'E') return;
int mines = countMines(board, r, c);
if (mines > 0) {
board[r][c] = (char) ('0' + mines);
return;
}
board[r][c] = 'B';
for (int dr = -1; dr <= 1; dr++) {
for (int dc = -1; dc <= 1; dc++) {
if (dr != 0 || dc != 0) reveal(board, r + dr, c + dc);
}
}
}
int countMines(vector<vector<char>>& board, int r, int c) {
int count = 0;
for (int dr = -1; dr <= 1; dr++) {
for (int dc = -1; dc <= 1; dc++) {
int nr = r + dr, nc = c + dc;
if (nr >= 0 && nc >= 0 && nr < (int) board.size() && nc < (int) board[0].size() && board[nr][nc] == 'M') count++;
}
}
return count;
}
};function updateBoard(board, click) {
const m = board.length, n = board[0].length;
const [r, c] = click;
if (board[r][c] === 'M') {
board[r][c] = 'X';
return board;
}
reveal(r, c);
return board;
function reveal(r, c) {
if (r < 0 || c < 0 || r >= m || c >= n || board[r][c] !== 'E') return;
const mines = countMines(r, c);
if (mines > 0) {
board[r][c] = String(mines);
return;
}
board[r][c] = 'B';
for (let dr = -1; dr <= 1; dr++) {
for (let dc = -1; dc <= 1; dc++) {
if (dr !== 0 || dc !== 0) reveal(r + dr, c + dc);
}
}
}
function countMines(r, c) {
let count = 0;
for (let dr = -1; dr <= 1; dr++) {
for (let dc = -1; dc <= 1; dc++) {
const nr = r + dr, nc = c + dc;
if (nr >= 0 && nc >= 0 && nr < m && nc < n && board[nr][nc] === 'M') count++;
}
}
return count;
}
}3Optimal (BFS reveal with a queue)
O(m · n)Each cell is queued at most once, because it stops being 'E' when queued, and each queued cell does two passes over its eight neighbours.O(m · n)The queue can hold O(m · n) cells; the board itself is the visited marker.The same flood fill, driven by a queue instead of recursion, so a huge blank area cannot overflow the call stack. A cell is set to 'B' the moment it is queued, which marks it as taken so it is never queued twice. When a cell is taken out of the queue, count its mines. A positive count overwrites the temporary 'B' with the digit and the cell spreads no further. A zero count leaves it 'B' and queues every neighbour that is still 'E'.
- If the clicked cell is 'M', set it to 'X' and return.
- Set the clicked cell to 'B' and put it in the queue.
- Take a cell out of the queue and count the mines around it. If the count is positive, write the digit and move on.
- Otherwise, for each neighbour that is 'E', set it to 'B' and queue it. Repeat until the queue is empty, then return the board.
class Solution {
public char[][] updateBoard(char[][] board, int[] click) {
int m = board.length, n = board[0].length;
if (board[click[0]][click[1]] == 'M') {
board[click[0]][click[1]] = 'X';
return board;
}
Queue<int[]> q = new ArrayDeque<>();
board[click[0]][click[1]] = 'B';
q.add(new int[] { click[0], click[1] });
while (!q.isEmpty()) {
int[] cell = q.poll();
int r = cell[0], c = cell[1], mines = 0;
for (int dr = -1; dr <= 1; dr++) {
for (int dc = -1; dc <= 1; dc++) {
int nr = r + dr, nc = c + dc;
if (nr >= 0 && nc >= 0 && nr < m && nc < n && board[nr][nc] == 'M') mines++;
}
}
if (mines > 0) {
board[r][c] = (char) ('0' + mines);
continue;
}
for (int dr = -1; dr <= 1; dr++) {
for (int dc = -1; dc <= 1; dc++) {
int nr = r + dr, nc = c + dc;
if (nr >= 0 && nc >= 0 && nr < m && nc < n && board[nr][nc] == 'E') {
board[nr][nc] = 'B';
q.add(new int[] { nr, nc });
}
}
}
}
return board;
}
}class Solution:
def updateBoard(self, board: List[List[str]], click: List[int]) -> List[List[str]]:
m, n = len(board), len(board[0])
if board[click[0]][click[1]] == 'M':
board[click[0]][click[1]] = 'X'
return board
q = deque()
board[click[0]][click[1]] = 'B'
q.append((click[0], click[1]))
while q:
r, c = q.popleft()
mines = 0
for dr in (-1, 0, 1):
for dc in (-1, 0, 1):
nr, nc = r + dr, c + dc
if 0 <= nr < m and 0 <= nc < n and board[nr][nc] == 'M':
mines += 1
if mines > 0:
board[r][c] = str(mines)
continue
for dr in (-1, 0, 1):
for dc in (-1, 0, 1):
nr, nc = r + dr, c + dc
if 0 <= nr < m and 0 <= nc < n and board[nr][nc] == 'E':
board[nr][nc] = 'B'
q.append((nr, nc))
return boardclass Solution {
public:
vector<vector<char>> updateBoard(vector<vector<char>>& board, vector<int>& click) {
int m = board.size(), n = board[0].size();
if (board[click[0]][click[1]] == 'M') {
board[click[0]][click[1]] = 'X';
return board;
}
queue<pair<int, int>> q;
board[click[0]][click[1]] = 'B';
q.push({click[0], click[1]});
while (!q.empty()) {
auto [r, c] = q.front();
q.pop();
int mines = 0;
for (int dr = -1; dr <= 1; dr++) {
for (int dc = -1; dc <= 1; dc++) {
int nr = r + dr, nc = c + dc;
if (nr >= 0 && nc >= 0 && nr < m && nc < n && board[nr][nc] == 'M') mines++;
}
}
if (mines > 0) {
board[r][c] = (char) ('0' + mines);
continue;
}
for (int dr = -1; dr <= 1; dr++) {
for (int dc = -1; dc <= 1; dc++) {
int nr = r + dr, nc = c + dc;
if (nr >= 0 && nc >= 0 && nr < m && nc < n && board[nr][nc] == 'E') {
board[nr][nc] = 'B';
q.push({nr, nc});
}
}
}
}
return board;
}
};function updateBoard(board, click) {
const m = board.length, n = board[0].length;
if (board[click[0]][click[1]] === 'M') {
board[click[0]][click[1]] = 'X';
return board;
}
const q = [];
board[click[0]][click[1]] = 'B';
q.push([click[0], click[1]]);
let head = 0;
while (head < q.length) {
const cell = q[head++];
const r = cell[0], c = cell[1];
let mines = 0;
for (let dr = -1; dr <= 1; dr++) {
for (let dc = -1; dc <= 1; dc++) {
const nr = r + dr, nc = c + dc;
if (nr >= 0 && nc >= 0 && nr < m && nc < n && board[nr][nc] === 'M') mines++;
}
}
if (mines > 0) {
board[r][c] = String(mines);
continue;
}
for (let dr = -1; dr <= 1; dr++) {
for (let dc = -1; dc <= 1; dc++) {
const nr = r + dr, nc = c + dc;
if (nr >= 0 && nc >= 0 && nr < m && nc < n && board[nr][nc] === 'E') {
board[nr][nc] = 'B';
q.push([nr, nc]);
}
}
}
}
return board;
}Edge cases to test
- Clicking a mine: only that cell changes, to 'X'
- A 1 x 1 board: 'M' becomes 'X' and 'E' becomes 'B'
- A board with no mines at all: every unrevealed cell becomes 'B'
- A cell surrounded by mines on all eight sides shows '8'
- Mines that touch only diagonally still count, and the reveal also spreads diagonally
- Cells revealed by earlier clicks ('B' and digits) must be left alone
- A 50 x 50 board with no mines: a recursive reveal can go about 2,500 calls deep
Hints
Hint 1
Write a helper that counts the mines among the up to eight neighbours of a cell.
Hint 2
A revealed cell either shows a number and stops, or is blank and asks all eight neighbours to be revealed too. That is a flood fill with eight directions.
Hint 3
Only 'E' cells take part in the reveal. Changing a cell from 'E' as soon as it is reached also marks it visited, so no cell is handled twice.
FAQ
What is the best time complexity for Minesweeper?
Optimal (BFS reveal with a queue) runs in O(m · n) time and O(m · n) extra space. Each cell is queued at most once, because it stops being 'E' when queued, and each queued cell does two passes over its eight neighbours.
Which pattern does Minesweeper use?
It is a graphs problem that uses the matrix graphs pattern. Other problems with the same pattern: Flood Fill, Maximum Number of Points From Grid Queries, Contain Virus.
Is there a brute force solution for Minesweeper?
Yes. Brute force (repeated sweeps) takes O((m · n)²) time and O(m · n) space. Do the reveal in rounds without any recursion or queue.
Which edge cases should I test for Minesweeper?
Clicking a mine: only that cell changes, to 'X'; A 1 x 1 board: 'M' becomes 'X' and 'E' becomes 'B'; A board with no mines at all: every unrevealed cell becomes 'B'; A cell surrounded by mines on all eight sides shows '8'; Mines that touch only diagonally still count, and the reveal also spreads diagonally; Cells revealed by earlier clicks ('B' and digits) must be left alone; A 50 x 50 board with no mines: a recursive reveal can go about 2,500 calls deep.