529. Minesweeper(Medium)

原题目:
  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']]

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.

题目大意如下:

  题目本质是解扫雷游戏,给出的一个矩形,由‘M’和‘E’组成,其中‘M’代表未揭示的雷‘E’代表还未揭示的空位。然后给出一个点,分三种情况:
  1.如果这个点的位置是‘M’那么用‘X’代替掉‘M’,游戏结束;
  2.如果点的位置是‘E’,并且这个点周围(上下左右还有对角总共八个点)都没有雷,那么用‘B’代替掉‘E’,然后依次揭示他周围的点;
  3.如果点的位置是‘E’,但这个点周围有雷,那么用它周围雷的个数(1到8)代替掉‘E’。
  最后,当没有地方可以揭示时,返回这个矩阵。

解题思路:

  这个题目是很典型的搜索类型题目,所以用DFS和BFS都可以。
  方法一:DFS

class Solution {
public:
    int count ;
    //to find adjacent mines
    int adj_mines(vector<vector<char>>& board , int x , int y){ 
        count = 0 ;
        for(int i = x - 1 ; i <= x + 1 ; ++i){
            for(int j = y - 1 ; j <= y + 1 ; ++j){
                //ensure i and j are valid
                if(i > -1 && i < board.size() && j > -1 && j < board[i].size() ) 
                    if(board[i][j] == 'M') count++ ;
            }
        }
        return count ;
    }

    vector<vector<char> > updateBoard(vector<vector<char>>& board, vector<int>& click) {
        int x = click[0] , y = click[1] ;
        //if reveal a mine, game over
        if(board[x][y] == 'M') {    
            board[x][y] = 'X' ;
            return board ;
        }
        //if there is no adjacent mines
        if(adj_mines(board , x , y) == 0){ 
            board[x][y] = 'B' ;
            for(int i = x - 1 ; i <= x + 1 ; ++i){
                for(int j = y - 1 ; j <= y + 1 ; ++j){
                    if( i > -1 && i < board.size() && j > -1 && j < board[i].size()){
                        click[0] = i ;
                        click[1] = j ;
                        //go on revealing next position
                        if(board[i][j] == 'E') updateBoard(board , click) ; 
                    }
                }
            }
        }
        else{
            //int to char
            board[x][y] = (char)(count + '0') ; 
        }
        return board ;
    }

};

运行结果:

DFS

  方法二:BFS(其实只要多加一个queue就行了)

class Solution {
public:
    int count ;
    //to find adjacent mines
    int adj_mines(vector<vector<char>>& board , int x , int y){ 
        count = 0 ;
        for(int i = x - 1 ; i <= x + 1 ; ++i){
            for(int j = y - 1 ; j <= y + 1 ; ++j){
                //ensure i and j are valid
                if(i > -1 && i < board.size() && j > -1 && j < board[i].size() ) 
                    if(board[i][j] == 'M') count++ ;
            }
        }
        return count ;
    }

    struct pos{
        int x ;
        int y ;
        pos(int a ,int b): x(a) , y(b){} 
    };

    vector<vector<char> > updateBoard(vector<vector<char>>& board, vector<int>& click) {
        int x = click[0] , y = click[1] ;
        queue<pos> q ;
        pos p(x , y) ;
        q.push(p) ;
        while(!q.empty()){
            //if reveal a mine, game over
            if(board[x][y] == 'M') {    
                board[x][y] = 'X' ;
                return board ;
            }
            x = q.front().x , y = q.front().y ;
            q.pop() ;
            //if there is no adjacent mines
            if(adj_mines(board , x , y) == 0){ 
                board[x][y] = 'B' ;
                for(int i = x - 1 ; i <= x + 1 ; ++i){
                    for(int j = y - 1 ; j <= y + 1 ; ++j){
                        if( i > -1 && i < board.size() && j > -1 && j < board[i].size())
                            if(board[i][j] == 'E'){
                                p.x = i ;
                                p.y = j ;
                                //avoid being pushed repeatedly
                                board[i][j] = 'B' ; 
                                q.push(p) ;   
                            }
                    }
                }
            }
            else{
                //int to char
                board[x][y] = (char)(count + '0') ;
            }

        }

        return board ;
    }

};

运行结果:

BFS
 
算法分析:
  相当于查找了整个矩形所以应该是O(n*m),即这个矩形的大小。

知识补充:
  在表示0到9的数字时,可以直接用char = char(int + ‘0’)把int类型直接转换成char类型。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
在 Java 中实现扫雷游戏,可以使用 Swing 库来创建图形界面。下面是一个示例代码,它满足您的要求: import java.awt.Dimension; import java.awt.GridLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.Random; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JMenu; import javax.swing.JMenuBar; import javax.swing.JMenuItem; import javax.swing.JOptionPane; public class MineSweeper extends JFrame implements ActionListener { private static final long serialVersionUID = 1L; private static final int EASY = 8; private static final int MEDIUM = 16; private static final int HARD = 24; private static final int MINES = 10; private JMenuItem newGameItem; private JMenuItem resetGameItem; private JMenuItem exitItem; private JButton[][] buttons; private boolean[][] mines; private boolean[][] revealed; private int rows; private int cols; private int minesLeft; public MineSweeper() { // 创建菜单栏 JMenuBar menuBar = new JMenuBar(); JMenu fileMenu = new JMenu("File"); newGameItem = new JMenuItem("New Game"); resetGameItem = new JMenuItem("Reset Game"); exitItem = new JMenuItem("Exit"); newGameItem.addActionListener(this); resetGameItem.addActionListener(this); exitItem.addActionListener(this); fileMenu.add(newGameItem); fileMenu.add(resetGameItem); fileMenu.add(exitItem); menuBar.add(fileMenu); setJMenuBar(menuBar); // 让玩家选择难度 Object[] options = { "Easy", "Medium", "Hard" }; int choice = JOptionPane.showOptionDialog(null, "Choose difficulty:", "Difficulty", JOptionPane.DEFAULT_OPTION, JOptionPane.PLAIN_MESSAGE, null, options, options[0]); if (choice == 0) { rows = EASY; cols = EASY; } else if (choice == 1) { rows = MEDIUM; cols = MEDIUM; } else { rows = HARD; cols = HARD; } // 初始化游戏 minesLeft = MINES; mines = new boolean[rows][cols]; revealed = new boolean[rows][cols]; buttons = new JButton
02-06
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值