Minesweeper (LeetCode 529): Solution and Explanation
Given a Minesweeper board and a click on a hidden square, return the board after the click is revealed: a mine explodes, a numbered square shows its mine count, and a blank square opens its neighbors recursively.
Intuition
The click either hits a mine, and that is the whole story, or it starts a flood fill over empty squares.
Each revealed square only needs the number of mines in its 3x3 neighborhood. If the count is positive the square shows the digit and the flood does not pass through it, which is exactly how the real game draws a border of numbers around an open area.
A zero count means every neighbor is safe, so all hidden neighbors are revealed the same way. BFS (or DFS) handles this spread, as long as a square is marked the moment it is queued so it is never processed twice.
Approach: BFS flood fill
- If
board[r][c]is'M', set it to'X'and return the board. - Otherwise mark the click as
'B'and push it into a queue. - Pop a square and count the
'M'cells among its 8 neighbors. - If the count is positive, write that digit into the square and do not expand it.
- If the count is zero, leave it
'B', mark every'E'neighbor as'B'and push it. - When the queue is empty, return the board.
Step-by-step example
board = 4 x 5 with one mine at (1,2), click = [3,0]
- (3,0) is not a mine. Mark it B and queue it.
- Pop (3,0): no mines nearby, so (2,0), (2,1) and (3,1) are marked and queued.
- Squares touching the mine, such as (2,1), count 1 mine and become '1' without spreading.
- The flood wraps around the mine along the bottom and right side until the queue empties.
- (0,2) is only reachable through numbered squares, so it stays hidden. The result matches the expected board.
Code: Python, Java, C++
1class Solution:
2 def updateBoard(self, board: List[List[str]], click: List[int]) -> List[List[str]]:
3 r, c = click
4 if board[r][c] == 'M':
5 board[r][c] = 'X'
6 return board
7 m, n = len(board), len(board[0])
8 board[r][c] = 'B'
9 queue = collections.deque([(r, c)])
10 while queue:
11 i, j = queue.popleft()
12 mines = 0
13 for di in (-1, 0, 1):
14 for dj in (-1, 0, 1):
15 x, y = i + di, j + dj
16 if 0 <= x < m and 0 <= y < n and board[x][y] == 'M':
17 mines += 1
18 if mines > 0:
19 board[i][j] = str(mines)
20 continue
21 for di in (-1, 0, 1):
22 for dj in (-1, 0, 1):
23 x, y = i + di, j + dj
24 if 0 <= x < m and 0 <= y < n and board[x][y] == 'E':
25 board[x][y] = 'B'
26 queue.append((x, y))
27 return board1class Solution {
2 public char[][] updateBoard(char[][] board, int[] click) {
3 int r = click[0], c = click[1];
4 if (board[r][c] == 'M') {
5 board[r][c] = 'X';
6 return board;
7 }
8 int m = board.length, n = board[0].length;
9 board[r][c] = 'B';
10 Deque<int[]> queue = new ArrayDeque<>();
11 queue.offer(new int[]{r, c});
12 while (!queue.isEmpty()) {
13 int[] cell = queue.poll();
14 int i = cell[0], j = cell[1], mines = 0;
15 for (int di = -1; di <= 1; di++) {
16 for (int dj = -1; dj <= 1; dj++) {
17 int x = i + di, y = j + dj;
18 if (x >= 0 && x < m && y >= 0 && y < n && board[x][y] == 'M') {
19 mines++;
20 }
21 }
22 }
23 if (mines > 0) {
24 board[i][j] = (char) ('0' + mines);
25 continue;
26 }
27 for (int di = -1; di <= 1; di++) {
28 for (int dj = -1; dj <= 1; dj++) {
29 int x = i + di, y = j + dj;
30 if (x >= 0 && x < m && y >= 0 && y < n && board[x][y] == 'E') {
31 board[x][y] = 'B';
32 queue.offer(new int[]{x, y});
33 }
34 }
35 }
36 }
37 return board;
38 }
39}1class Solution {
2public:
3 vector<vector<char>> updateBoard(vector<vector<char>>& board, vector<int>& click) {
4 int r = click[0], c = click[1];
5 if (board[r][c] == 'M') {
6 board[r][c] = 'X';
7 return board;
8 }
9 int m = board.size(), n = board[0].size();
10 board[r][c] = 'B';
11 queue<pair<int, int>> q;
12 q.push({r, c});
13 while (!q.empty()) {
14 int i = q.front().first, j = q.front().second;
15 q.pop();
16 int mines = 0;
17 for (int di = -1; di <= 1; di++) {
18 for (int dj = -1; dj <= 1; dj++) {
19 int x = i + di, y = j + dj;
20 if (x >= 0 && x < m && y >= 0 && y < n && board[x][y] == 'M') {
21 mines++;
22 }
23 }
24 }
25 if (mines > 0) {
26 board[i][j] = '0' + mines;
27 continue;
28 }
29 for (int di = -1; di <= 1; di++) {
30 for (int dj = -1; dj <= 1; dj++) {
31 int x = i + di, y = j + dj;
32 if (x >= 0 && x < m && y >= 0 && y < n && board[x][y] == 'E') {
33 board[x][y] = 'B';
34 q.push({x, y});
35 }
36 }
37 }
38 }
39 return board;
40 }
41};Time and space complexity
O(m * n)
Each square is queued at most once, and handling it looks at a constant 8 neighbors.
O(m * n)
The queue can hold a large part of the board in the worst case, such as a board with no mines.
Other approaches
Recursive DFS (time O(m * n), space O(m * n))
Reveal the clicked square, and if its count is zero call the same function on each hidden neighbor. It is shorter, but a 50 x 50 open board can recurse 2500 levels deep, which risks stack overflow in some languages.
Precomputed counts (time O(m * n), space O(m * n))
First compute the mine count of every square in one pass, then flood fill using the table. It does the same work, just split into two phases, and is handy if many clicks will be simulated.
Common mistakes
- Expanding from numbered squares. Only a zero count spreads; a digit is a wall.
- Marking squares only when they are popped, which lets the same square enter the queue several times.
- Forgetting the diagonals. Both the mine count and the spread use all 8 neighbors.
- Revealing other mines. The flood only opens
'E'squares, so an'M'is never touched except by a direct click.
Frequently asked questions
Why is it safe to mark a queued square as 'B' before counting its mines?
The count only looks for 'M' cells, so a temporary 'B' does not change anyone's count. When the square is popped, its real value (a digit or B) overwrites the mark.
Does BFS give a different board than DFS?
No. The set of revealed squares and their values depend only on the board and the click, not on the order of the flood.
What happens if the click is on an empty square next to a mine?
Only that square changes, to its mine count. Nothing spreads from a numbered square.