[leetcode] 529. Minesweeper

Let's play the minesweeper game (Wikipediaonline game)!

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.

Example 1:

Input: 

[['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']]

Explanation:

Example 2:

Input: 

[['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']]

Explanation:

Note:

  1. The range of the input matrix's height and width is [1,50].
  2. The click position will only be an unrevealed square ('M' or 'E'), which also means the input board contains at least one clickable square.
  3. The input board won't be a stage when game is over (some mines have been revealed).
  4. For simplicity, not mentioned rules should be ignored in this problem. For example, you don't need to reveal all the unrevealed mines when the game is over, consider any cases that you will win the game or flag any squares.

这道题是小游戏扫雷,题目难度为Medium。

这类题目可以分别通过广度优先搜索和深度优先搜索两种方法来解决。

广度优先搜索在搜索过程中借助队列,将遍历位置相邻的位置逐个存入队列来完成广度优先搜索。游戏规则不再详述,题目复杂的地方在点到‘E’且相邻位置没有‘M’时,需要将相邻位置的‘E’依次做同样的操作,这也是需要做广度优先搜索的原因。搜索过程中要避免将同一位置重复存入队列中,注意代码中board[rr][cc] = 'B'这句,将插入队列待处理的位置先标记为‘B’以避免重复。具体代码:

class Solution {
public:
    vector<vector<char>> updateBoard(vector<vector<char>>& board, vector<int>& click) {
        queue<pair<int, int>> que;
        que.push(make_pair(click[0], click[1]));
        int m = board.size(), n = board[0].size();
        
        while(!que.empty()) {
            pair<int, int> cur = que.front();
            que.pop();
            int r = cur.first;
            int c = cur.second;
            
            if(board[r][c] == 'M') {
                board[r][c] = 'X';
                return board;
            }
            else {
                int mineCnt = 0;
                for(int i=-1; i<=1; ++i) {
                    for(int j=-1; j<=1; ++j) {
                        int rr = r + i;
                        int cc = c + j;
                        if((i == 0 && j == 0) || rr < 0 || rr >= m || cc < 0 || cc >= n) 
    ​    ​    ​    ​    ​    ​    ​continue;
                        if(board[rr][cc] == 'M') ++mineCnt;
                    }
                }
                
                if(mineCnt) {
                    board[r][c] = '0' + mineCnt;
                }
                else {
                    board[r][c] = 'B';
                    for(int i=-1; i<=1; ++i) {
                        for(int j=-1; j<=1; ++j) {
                            int rr = r + i;
                            int cc = c + j;
                            if((i == 0 && j == 0) || rr < 0 || rr >= m || cc < 0 || cc >= n)
    ​    ​    ​    ​    ​    ​    ​    ​continue;
                            if(board[rr][cc] == 'E') {
                                que.push(make_pair(rr, cc));
                                board[rr][cc] = 'B';
                            }
                        }
                    }
                }
            }
        }
        return board;
    }
};
深度优先搜索在搜索过程中需要递归。在 点到‘E’且相邻位置没有‘M’时, 采用深度优先的策略通过递归逐个遍历相邻位置。具体代码:
class Solution {
    void dfsUpdate(vector<vector<char>>& board, int r, int c, int m, int n) {
        if(board[r][c] == 'M') {
            board[r][c] = 'X';
        }
        else if(board[r][c] == 'E') {
            int mineCnt = 0;
            for(int i=-1; i<=1; ++i) {
                for(int j=-1; j<=1; ++j) {
                    int rr = r + i;
                    int cc = c + j;
                    if((i == 0 && j == 0) || rr < 0 || rr >= m || cc < 0 || cc >= n)
    ​    ​    ​    ​    ​    ​continue;
                    if(board[rr][cc] == 'M') ++mineCnt;
                }
            }
            
            if(mineCnt == 0) {
                board[r][c] = 'B';
                for(int i=-1; i<=1; ++i) {
                    for(int j=-1; j<=1; ++j) {
                        int rr = r + i;
                        int cc = c + j;
                        if((i == 0 && j == 0) || rr < 0 || rr >= m || cc < 0 || cc >= n)
    ​    ​    ​    ​    ​    ​    ​continue;
                        dfsUpdate(board, rr, cc, m, n);
                    }
                }
            }
            else board[r][c] = '0' + mineCnt;
        }
    }
public:
    vector<vector<char>> updateBoard(vector<vector<char>>& board, vector<int>& click) {
        dfsUpdate(board, click[0], click[1], board.size(), board[0].size());
        return board;
    }
};


### 关于割点和割边的算法练习题 #### 割点与割边的概念 在图论中,割点是指如果删除某个顶点及其关联的所有边之后,原连通图被分割成两个或更多不相连的部分,则该顶点称为割点。同样地,割边(也称桥)是指当删除某条边后,原连通图也被分割成两部分或多部分[^4]。 以下是几个经典的割点和割边相关题目集合: --- #### 经典题目集合 1. **POJ 3177 Redundant Paths** - 描述:给定一个无向图,询问至少需要添加多少条边才能使整个图变成双连通图。 - 解法提示:利用 Tarjan 算法找到所有的桥,并通过计算森林中的叶子节点数量来推导所需增加的最少边数[^5]。 2. **UVA 10189 Minesweeper (改编版本)** - 描述:在一个网格地图上模拟炸弹爆炸的影响范围,其中某些位置可能成为割点或者割边的关键路径。 - 解法提示:可以扩展为动态规划加 DFS 的形式,重点在于如何快速定位哪些区域会因为特定点/边而断开连接。 3. **Codeforces Round #XYZ Problem A/B/C/D/E/F/G/H/I/J/K/L/M/N/O/P/Q/R/S/T/U/V/W/X/Y/Z** - 多次比赛中都出现了基于 Tarjan 算法的应用实例,比如 CF 场景下的 “Bridge Finding” 或者类似的变种问题。 4. **LeetCode Premium Problems** - 虽然 LeetCode 上免费资源较少提及显式的“割点”概念,但在一些高级付费课程里确实存在针对此类主题设计的教学案例,尤其是涉及到复杂网络拓扑结构分析时更为明显。 5. **HDU OJ Series on Graph Theory Challenges** - HDU 平台提供了大量围绕图理论展开的实际操作型习题集锦,其中包括但不限于检测简单路径上的所有潜在瓶颈——也就是我们所说的割点和桥梁。 ```python def find_bridges(graph, n): result = [] visited = [False]*n disc = [-1]*n low = [-1]*n parent = [-1]*n time = [0] def dfs(u): children = 0 visited[u] = True disc[u] = low[u] = time[0] time[0] += 1 for v in graph[u]: if not visited[v]: parent[v] = u children += 1 dfs(v) low[u] = min(low[u], low[v]) if low[v] > disc[u]: result.append((u,v)) elif v != parent[u]: low[u] = min(low[u], disc[v]) for i in range(n): if not visited[i]: dfs(i) return result ``` 上述代码片段展示了如何运用深度优先搜索技术去发现存在于任意无向图内的全部桥梁列表。 --- ####
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值