Minesweeper
Update a Minesweeper board after one click, opening blank areas and stopping at numbered squares.
A Minesweeper board is given as a grid of characters, boardclick
: a mine that is still hidden;'M' : an empty square that is still hidden;'E' : a revealed blank square, with no mine among its 8 neighbours (the squares above, below, left, right and on the four diagonals);'B' to'1' : a revealed square with that many mines among its 8 neighbours;'8' : a revealed mine.'X'
Return the board after the click, revealing squares by these rules:
- If the clicked square is a mine,
, it becomes'M' and nothing else changes.'X' - When an
square is revealed and has no mine among its neighbours, it becomes'E' , and its hidden neighbours are revealed by the same rules.'B' - When an
square is revealed and has at least one mine among its neighbours, it becomes the digit for that count, and the reveal goes no further from it.'E'
Example 1
Output: [["B","1","E","1","B"],["B","1","M","1","B"],["B","1","1","1","B"],["B","B","B","B","B"]]
Example 2
Output: [["B","1","E","1","B"],["B","1","X","1","B"],["B","1","1","1","B"],["B","B","B","B","B"]]
The Idea
If you have played Minesweeper, you know the moment when one click opens a whole area of the board at once. That area is what this problem asks for. Example 1 has a board of 4 rows and 5 columns, with one hidden mine at row 1, column 2, written (1, 2). The player clicks (3, 0), the bottom-left corner.
Look at the picture below. On the left is the board before the click, with the clicked square (3, 0) outlined. On the right is the board after the click.
Square (3, 0) has no mine around it, so it becomes B. A blank square gives the player no clue, so the game opens its neighbours too: (2, 0), (2, 1) and (3, 1). Squares (2, 0) and (3, 1) are blank as well, and they open their own neighbours. Square (2, 1) touches the mine at (1, 2) on a diagonal, so it becomes 1 and opens nothing.
Carry on like this and the teal B squares spread along the bottom row and up both sides, while the blue 1 squares form a ring around the mine. Now find (0, 2), outlined at the top of the right board. It still reads E. Why did the reveal never reach it? Apart from the mine, its neighbours are (0, 1), (0, 3), (1, 1) and (1, 3), and all four are numbers. The picture's note says it: (0, 2) stays E because only numbers touch it.
So the reveal spreads through blank squares and stops at numbers. Example 2 is the other case: the player clicks the mine at (1, 2), it turns into X, and nothing else changes.
Think of each square as a point, linked to each of its neighbours. Points with links between them form a graph, and the reveal is a walk through that graph that starts at the click and only moves on from blank squares. Following one path as far as it goes before backing up to try the next is called depth-first search, or DFS. Spreading over a grid this way is often called flood fill.
Solution Approach
Turning the reveal into code means settling four things: what a click on a mine does, how to count nearby mines, how a blank square opens its neighbours, and how the spreading ends.
Clicking a mine
What if the click lands on 'M''X'
Counting the mines around a square
How do we visit the 8 neighbours of a square at row rc'E'
Opening the neighbours of a blank square
How does one revealed square reveal more? A method reveal(board, r, c)'B'
Stopping at revealed squares
What keeps two blank squares from opening each other forever? Square (3, 0) opens (3, 1), and (3, 1) then looks back at (3, 0). The answer is a check at the top of reveal'E''B''B'
Java Solution
The method updateBoard
- First, read the clicked row and column from
intoclick andr . Ifc isboard[r][c] , set it to'M' and return the board.'X' - Otherwise, call
, the method that reveals one square. It returns straight away if (reveal(board, r, c) ,r ) is off the board or the square there is notc .'E' - Inside
, count the mines around the square intoreveal . Two loops, one inside the other, movemines anddr from -1 to 1, and each position (dc ,r + dr ) that is on the board and holdsc + dc adds one.'M' - If
is above 0, writemines , which turns a count of 2 into the character(char) ('0' + mines) , and return without visiting any neighbour.'2' - If
is 0, writemines . Then two more loops over'B' anddr calldc on each of the 8 neighbours, skipping the case where both are 0, which is the square itself.reveal - When the first call to
returns, every square the click opens is revealed, andreveal returns the changed board.updateBoard
The mainshow
import java.util.Arrays;
public class Minesweeper {
public static char[][] updateBoard(char[][] board, int[] click) {
int r = click[0];
int c = click[1];
if (board[r][c] == 'M') {
board[r][c] = 'X'; // clicked a mine: game over
return board;
}
reveal(board, r, c);
return board;
}
private static void reveal(char[][] board, int r, int c) {
if (r < 0 || r >= board.length || c < 0 || c >= board[0].length) {
return; // off the board
}
if (board[r][c] != 'E') {
return; // only hidden empty squares change
}
int mines = 0;
for (int dr = -1; dr <= 1; dr++) {
for (int dc = -1; dc <= 1; dc++) {
int nr = r + dr;
int nc = c + dc;
if (nr >= 0 && nr < board.length && nc >= 0 && nc < board[0].length
&& board[nr][nc] == 'M') {
mines++;
}
}
}
if (mines > 0) {
board[r][c] = (char) ('0' + mines); // a number stops the spread
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);
}
}
}
}
static char[][] parse(String... rows) {
char[][] board = new char[rows.length][];
for (int i = 0; i < rows.length; i++) {
board[i] = rows[i].toCharArray();
}
return board;
}
static void show(String label, char[][] board) {
System.out.println(label);
for (char[] row : board) {
System.out.println(Arrays.toString(row));
}
}
public static void main(String[] args) {
char[][] board = parse("EEEEE", "EEMEE", "EEEEE", "EEEEE");
show("Example 1, click (3, 0):", updateBoard(board, new int[] {3, 0}));
show("Example 2, click (1, 2):", updateBoard(board, new int[] {1, 2}));
show("Two mines nearby, click (1, 1):",
updateBoard(parse("MEE", "EEE", "EEM"), new int[] {1, 1}));
show("No mines at all, click (0, 0):",
updateBoard(parse("EEE", "EEE"), new int[] {0, 0}));
}
}
Running it prints:
Example 1, click (3, 0):
[B, 1, E, 1, B]
[B, 1, M, 1, B]
[B, 1, 1, 1, B]
[B, B, B, B, B]
Example 2, click (1, 2):
[B, 1, E, 1, B]
[B, 1, X, 1, B]
[B, 1, 1, 1, B]
[B, B, B, B, B]
Two mines nearby, click (1, 1):
[M, E, E]
[E, 2, E]
[E, E, M]
No mines at all, click (0, 0):
[B, B, B]
[B, B, B]
The four rows under "Example 1, click (3, 0):" match the right board in the picture: B down both sides and along the bottom, 1s around the M, and the hidden E in the first row, [B, 1, E, 1, B]
Under "Two mines nearby", the middle square has mines at (0, 0) and (2, 2) on its diagonals, so it shows 2. Because 2 is a number, nothing else opens, and the other six squares still read E. With no mines at all, the last board shows a single click in the corner turning all six squares into B.
Why must a number return instead of going on to its neighbours? A variant that writes the digit and then keeps calling reveal
Spreading from numbers too, click (3, 0):
[B, 1, 1, 1, B]
[B, 1, M, 1, B]
[B, 1, 1, 1, B]
[B, B, B, B, B]
The first row now reads [B, 1, 1, 1, B]
Complexity
The work is one call of reveal
- Time: O(m × n) for a board of m rows and n columns, because each square changes from
at most once, and the call that changes it checks 9 positions and makes at most 8 more calls.'E' - Space: O(m × n), because the board is changed in place but the chain of unfinished
calls can wind through most of the squares on a board with few mines.reveal
The same flood fill over a grid is used in