(dfs) leetcode 528. Minesweeper

博客介绍了扫雷游戏的操作思路,与小岛问题类似。主要有四个操作,点到未发现炸弹‘M’,该位置变为‘X’游戏结束;点到四周无炸弹的‘E’,变为‘B’并递归遍历附近格子;点到四周有炸弹的‘E’,变为代表炸弹个数的数字;最后返回board。

思路:这道题和小岛那道有些类似,主要是实现以下这四个操作:

  1. If a mine ('M') is revealed, then the game is over - change it to 'X'.   若点到M,它是代表还未发现的炸弹,则该位置变为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.    如果点到E,它的四周没有炸弹,则该位置变为B,然后递归遍历它附近的8个格子(用dfs)。
  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.   如果点到E,它的四周至少有一个炸弹,则把该位置变为1-8(为炸弹的个数)。
  4. Return the board when no more squares will be revealed.   返回board。
class Solution {
public:
    int dx[8] = {-1,-1,-1, 1, 1, 1,0,0};
    int dy[8] = {-1, 0, 1,-1, 0, 1,-1,1};
    vector<vector<char>> updateBoard(vector<vector<char>>& board, vector<int>& click) {
        //If a mine ('M') is revealed, then the game is over - change it to 'X'.
        int x = click[0], y = click[1];
        if(board[x][y]=='M'){
            board[x][y] = 'X';
            return board;
        }
        //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.
        dfs(board, x, y);
        return board;
        
    }
    
    void dfs(vector<vector<char>>& board, int x, int y){
        int m = board.size(), n = board[0].size();
        if(x<0 || x>=m || y<0 || y>=n || board[x][y] !='E')
            //出口
            return;
        int num = numOfBombs(board, x, y);
        //1. no adjacenet mine
        if(num==0){
            board[x][y] = 'B';
            for(int i=0; i<8; i++){
                int newX = x + dx[i], newY = y + dy[i];
                dfs(board, newX, newY);
            }
        }
        else{
            //2. at least one mine
            board[x][y] = num +'0';
        }
    }
    
    int numOfBombs(vector<vector<char>>& board, int x, int y){
        int num = 0;  //记录附近8个格子中炸弹的个数
        int m = board.size(), n = board[0].size();
        for(int i=0; i<8; ++i){
            //遍历附近的8格
            int newX = x +dx[i], newY = y +dy[i];
            if(newX<0 || newX>=m || newY<0 || newY>=n)
                continue;
            if(board[newX][newY]=='M' || board[newX][newY]=='X')
                ++num;
        }
        return num;
    }
};

 

转载于:https://www.cnblogs.com/Bella2017/p/11165914.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值