> For the complete documentation index, see [llms.txt](https://joshualbarb.gitbook.io/leetcode-problems/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://joshualbarb.gitbook.io/leetcode-problems/graphs/minesweeper.md).

# Minesweeper

## Problem

Let's play the minesweeper game ([Wikipedia](https://en.wikipedia.org/wiki/Minesweeper_\(video_game\)), [online game](http://minesweeperonline.com/))!

You are given a 2D char matrix representing the game board. **'M'** represents an **unrevealed** mine, **'E'** represents an **unrevealed** empty square, **'B'** represents a **revealed** blank square that has no adjacent (above, below, left, right, and all 4 diagonals) mines, **digit** ('1' to '8') represents how many mines are adjacent to this **revealed** square, and finally **'X'** represents a **revealed** mine.

Now given the next click position (row and column indices) 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 - change it to **'X'**.
2. If an empty square ('E') with **no adjacent mines** is revealed, then change it to 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.

![](/files/-MRMxPqyGtcYMQnqB7EN)

![](/files/-MRMxYGxsy9MZeozfr8S)

### Thought Process

![](/files/-MRN3mBNPkCwsds8j7tx)

* There's a BFS solution and DFS solution. I implemented both

## Solution&#x20;

```
from collections import deque

class Solution:
    def updateBoard(self, board: List[List[str]], click: List[int]) -> List[List[str]]:
        
        visited = set()
        q = deque()
        i, j = click[0], click[1]
        q.append([i,j])
        visited.add((i,j))
        
        directions = [[-1,0], [1,0], [0,-1], [0,1],[-1,-1], [-1,1], [1,-1], [1,1]]
        
        while q:
            coor = q.popleft()
            print(q)
            x, y = coor[0], coor[1]
            print(x,y)
        
            if board[x][y] == 'M':
                board[x][y] = 'X'
            
            else: #see how many bombs are around
                
                count = 0
                for d in directions:
                    newX, newY = x+d[0], y+d[1]
                  
                    
                    if newX < 0 or newX >= len(board) or newY < 0 or newY >= len(board[0]):
                        continue
                    elif board[newX][newY] == 'M' or board[newX][newY] == 'X' :
                        count+=1
                        
                if count != 0: #we don't want to do BFS if a bomb is near
                    board[x][y] = str(count)
                    
                else:
                    board[x][y] = 'B'
                    
                    for dd in directions:
                        newX, newY = x+dd[0], y+dd[1]
                        if newX < 0 or newX >= len(board) or newY < 0 or newY >= len(board[0]) or (newX, newY) in visited:
                            continue
                        
                        if board[newX][newY] == 'E':
                            q.append([newX, newY])
                            
                            visited.add((newX, newY))
            
        return board
                        
```

### DFS Solution

```
class Solution:
    def checkMines(self, x, y, board):
        numMines = 0
        for i in range(x-1,x+2):
            for j in range(y-1, y+2):
                if i >= 0 and i < len(board) and j >= 0 and j < len(board[i]) and board[i][j] == 'M':
                    numMines+=1
        return numMines
        
    def updateBoard(self, board: List[List[str]], click: List[int]) -> List[List[str]]:
        
        x, y = click[0], click[1]
        
        if board[x][y] == 'M':
            board[x][y] = 'X'
              
        else:
            mines = self.checkMines(x,y,board)
            if mines:
                board[x][y] = str(mines)
            else: #no mines adjacent
                board[x][y] = 'B'
                for i in range(x-1,x+2):
                    for j in range(y-1, y+2):
                        if i >= 0 and i < len(board) and j >= 0 and j < len(board[i]) and board[i][j] != 'B':
                            self.updateBoard(board, [i,j])
        return board
        
```

## Time Complexity

* **Time:** O(m\*n) for both BFS and DFS since we are traversing through the matrix

* **Space**: O(m\*n) for both BFS and DFS. With a queue we are storing every cell and with recusrion the call stack will be m\*n.&#x20;


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://joshualbarb.gitbook.io/leetcode-problems/graphs/minesweeper.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
