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, board, and click holds the row and column of the square the player clicks. Each square holds one of these characters:

Return the board after the click, revealing squares by these rules:

  1. If the clicked square is a mine, 'M', it becomes 'X' and nothing else changes.
  2. When an 'E' square is revealed and has no mine among its neighbours, it becomes 'B', and its hidden neighbours are revealed by the same rules.
  3. When an 'E' 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.
Example 1
Input: board = [["E","E","E","E","E"],["E","E","M","E","E"],["E","E","E","E","E"],["E","E","E","E","E"]], click = [3,0]
Output: [["B","1","E","1","B"],["B","1","M","1","B"],["B","1","1","1","B"],["B","B","B","B","B"]]
Example 2
Input: board = [["B","1","E","1","B"],["B","1","M","1","B"],["B","1","1","1","B"],["B","B","B","B","B"]], click = [1,2]
Output: [["B","1","E","1","B"],["B","1","X","1","B"],["B","1","1","1","B"],["B","B","B","B","B"]]
Solution

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.

Example 1 before and after clicking square (3, 0). Blank B squares spread from the corner along the bottom row and up both sides, the squares around the mine at (1, 2) become 1, and square (0, 2) stays E.

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'? Then the game is over. The square becomes 'X' and the board is returned at once, with nothing else revealed.

Counting the mines around a square

How do we visit the 8 neighbours of a square at row r and column c? Add -1, 0 or 1 to the row and -1, 0 or 1 to the column, with two loops, one inside the other. That gives 9 positions, including the square itself, which does no harm because the square is 'E', not a mine. A square on the edge has fewer neighbours, so each position is checked against the board's size before it is read.

Opening the neighbours of a blank square

How does one revealed square reveal more? A method reveal(board, r, c) handles one square. If its mine count is above 0, it writes the digit and returns. If the count is 0, it writes 'B' and calls itself on each of the 8 neighbours. A method that calls itself is called recursive. Each call finishes its whole spread before the caller moves to its next neighbour, which is exactly the depth-first search from above.

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: it returns at once unless the square is still 'E'. A square is written as 'B' before its neighbours are visited, so (3, 1) finds 'B' at (3, 0) and leaves it alone. The same check skips mines and numbers, and an earlier check skips positions off the board.

Java Solution

The method updateBoard works in these steps:

  1. First, read the clicked row and column from click into r and c. If board[r][c] is 'M', set it to 'X' and return the board.
  2. Otherwise, call reveal(board, r, c), the method that reveals one square. It returns straight away if (r, c) is off the board or the square there is not 'E'.
  3. Inside reveal, count the mines around the square into mines. Two loops, one inside the other, move dr and dc from -1 to 1, and each position (r + dr, c + dc) that is on the board and holds 'M' adds one.
  4. If mines is above 0, write (char) ('0' + mines), which turns a count of 2 into the character '2', and return without visiting any neighbour.
  5. If mines is 0, write 'B'. Then two more loops over dr and dc call reveal on each of the 8 neighbours, skipping the case where both are 0, which is the square itself.
  6. When the first call to reveal returns, every square the click opens is revealed, and updateBoard returns the changed board.

The main method runs both examples on the same board, one after the other, then a click on a square between two mines and a click on a board with no mines. A helper, show, prints each board one row per line.

Java
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:

Output
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]. Example 2 clicks that same board at the mine, and the only change is in the second row, where M has become X.

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 prints this for Example 1:

Output
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]: the spread went on through the 1s and opened (0, 2), which the rules keep hidden until the player clicks it.

Complexity

The work is one call of reveal for every square that gets revealed, plus the calls that return at once.

  • Time: O(m × n) for a board of m rows and n columns, because each square changes from 'E' at most once, and the call that changes it checks 9 positions and makes at most 8 more calls.
  • Space: O(m × n), because the board is changed in place but the chain of unfinished reveal calls can wind through most of the squares on a board with few mines.

The same flood fill over a grid is used in Number of Islands.