Minesweeper LeetCode Solution

Difficulty Level Medium
Frequently asked in Amazon Apple Bloomberg Cruise Automation DocuSign Facebook Google Microsoft Pinterest Square Uber Zillow
LiveRamp ToptalViews 213

Problem Statement

Minesweeper LeetCode Solution – Let’s play the minesweeper game (Wikipediaonline game)!

You are given an m x n char matrix board representing the game board where:

  • 'M' represents an unrevealed mine,
  • 'E' represents an unrevealed empty square,
  • 'B' represents a revealed blank square that has no adjacent mines (i.e., above, below, left, right, and all 4 diagonals),
  • digit ('1' to '8') represents how many mines are adjacent to this revealed square, and
  • 'X' represents a revealed mine.

You are also given an integer array click where click = [clickr, clickc] represents the next click position among all the unrevealed squares ('M' or 'E').

Return the board after revealing this position according to the following rules:

  1. If a mine 'M' is revealed, then the game is over. You should change it to 'X'.
  2. If an empty square 'E' with no adjacent mines is revealed, then change it to a revealed blank 'B' and all of its adjacent unrevealed squares should be revealed recursively.
  3. If an empty square 'E' with at least one adjacent mine is revealed, then change it to a digit ('1' to '8') representing the number of adjacent mines.
  4. Return the board when no more squares will be revealed.

Example

Test Case 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″,”X”,”1″,”B”],[“B”,”1″,”1″,”1″,”B”],[“B”,”B”,”B”,”B”,”B”]]

Minesweeper LeetCode Solution

Approach:

This is a typical Search problem, either by using DFS or BFS. Search rules:

  1. If click on a mine (‘M‘), mark it as ‘X‘, stop further search.
  2. If click on an empty cell (‘E‘), depends on how many surrounding mine:
    2.1 Has surrounding mine(s), mark it with the number of surrounding mine(s), and stop further search.
    2.2 No surrounding mine, mark it as ‘B‘, continue to search its 8 neighbors.

the idea is to follow the rules defined in the question.

  1. when you click mine (‘M’)—-> change it to ‘X’
  2. when you click ‘E’ —> do dfs search from there
    a. count for adjacent mines.
    if there is no mine then you can visit them and make them ‘B’
    else if there are mines then you can’t visit them thereby stopping the dfs search.(assign the number of mines here and return)

Code for Minesweeper

C++ Program

class Solution {
int rows,cols;
    int X[8] = {0,-1,-1,-1,0,1,1,1};
    int Y[8] = {1,1,0,-1,-1,-1,0,1};
    int countMines(vector<vector<char>>& board,int x,int y){
        int count = 0;
        for(int i=0;i<8;i++){
            int dx = x + X[i], dy = y + Y[i];
            if(dx>=0 && dy>=0 && dx<rows && dy<cols && board[dx][dy]=='M')
                count++;
        }
        return count;
    }
    void dfs(vector<vector<char>>& board,int x, int y){
        
        int mines = countMines(board,x,y);
        if(mines == 0)
            board[x][y] = 'B';
        else{
            board[x][y] = char(mines+'0');
            return;
        }
        for(int i=0;i<8;i++){
            int dx = x + X[i], dy = y + Y[i];
            if(dx>=0 && dy>=0 && dx<rows && dy<cols && board[dx][dy]=='E')
                dfs(board,dx,dy);
        }
    }
public:
    vector<vector<char>> updateBoard(vector<vector<char>>& board, vector<int>& click) {
        if(board.size()==0 || board[0].size()==0)
            return board;
        rows = board.size(); cols = board[0].size();
        int x = click[0], y = click[1];
        if(board[x][y] == 'M')
            board[x][y] = 'X';
        else if(board[x][y] == 'E')
            dfs(board,x,y);
        return board;
    }
};

Java Program

class Solution {
   public char[][] updateBoard(char[][] board, int[] click) {
        int m = board.length, n = board[0].length;
        int row = click[0], col = click[1];
        
        if (board[row][col] == 'M') { // Mine
            board[row][col] = 'X';
        }
        else { // Empty
            // Get number of mines first.
            int count = 0;
            for (int i = -1; i < 2; i++) {
                for (int j = -1; j < 2; j++) {
                    if (i == 0 && j == 0) continue;
                    int r = row + i, c = col + j;
                    if (r < 0 || r >= m || c < 0 || c < 0 || c >= n) continue;
                    if (board[r][c] == 'M' || board[r][c] == 'X') count++;
                }
            }
            
            if (count > 0) { // If it is not a 'B', stop further DFS.
                board[row][col] = (char)(count + '0');
            }
            else { // Continue DFS to adjacent cells.
                board[row][col] = 'B';
                for (int i = -1; i < 2; i++) {
                    for (int j = -1; j < 2; j++) {
                        if (i == 0 && j == 0) continue;
                        int r = row + i, c = col + j;
                        if (r < 0 || r >= m || c < 0 || c < 0 || c >= n) continue;
                        if (board[r][c] == 'E') updateBoard(board, new int[] {r, c});
                    }
                }
            }
        }
        
        return board;
    }
}

Complexity Analysis for Minesweeper LeetCode Solution

Time Complexity: O(8 * M * N) = O(M * N).

Space Complexity: O(M + N) –> Last level contains 2M+2N cells. Thus it can * grow maximum to 2M+2N.

Translate »